How to add multiple headers in Angular 5 HttpInterceptor

后端 未结 6 705
情话喂你
情话喂你 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:46

    Edit: Following suggestions in comments I have unified both answers

    Overwriting all headers

    @Injectable()
    export class fwcAPIInterceptor implements HttpInterceptor {
      intercept (req: HttpRequest, next: HttpHandler): Observable> {
    
      const authReq = req.clone({
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'Authorization': 'my-auth-token'
        })
      });
    
      console.log('Intercepted HTTP call', authReq);
    
      return next.handle(authReq);
    }
    

    Adding more headers without overwriting (credits to Ketan Patil - see answer in this post)

    const authReq = req.clone({
        headers: req.headers.set('Content-Type', 'application/json')
            .set('header2', 'header 2 value')
            .set('header3', 'header 3 value')
    });
    

提交回复
热议问题