How to add multiple headers in Angular 5 HttpInterceptor

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

    in your interceptor file

    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
    import {Injectable} from '@angular/core';
    import {Observable} from 'rxjs';
    @Injectable()
    export class fwcAPIInterceptor implements HttpInterceptor {
      intercept (req: HttpRequest, next: HttpHandler): Observable> {
    
      const auth = req.clone({
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'Auth-Token': 'jwtToken'
        })
      });
    
    
    
      return next.handle(auth);
    }
    
    
    
     **in app module**
    
    import {HTTP_INTERCEPTORS} from '@angular/common/http';
    
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule
      ],
      providers: [
        {provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true},
      ],
      bootstrap: [AppComponent]
    })
    

提交回复
热议问题