How to add multiple headers in Angular 5 HttpInterceptor

后端 未结 6 682
情话喂你
情话喂你 2020-12-09 15:16

I\'m trying to learn how to use HttpInterceptor to add a couple of headers to each HTTP request the app do to the API. I\'ve got this interceptor:



        
6条回答
  •  时光说笑
    2020-12-09 15:37

      const modifiedReq = req.clone({
          url: this.setUrl(req.url),
          headers: this.addExtraHeaders(req.headers)
        });
    

    And the method:

    private addExtraHeaders(headers: HttpHeaders): HttpHeaders {
      headers = headers.append('myHeader', 'abcd');
      return headers;
    } 
    

    The method .append creates a new HttpHeaders object adds myHeader and returns the new object.

    Using this solution means that you can also use multiple interceptors because you will not overwrite your headers.

提交回复
热议问题