Add multiple HTTP Interceptors to Angular Application

前端 未结 1 1258
面向向阳花
面向向阳花 2021-01-30 08:16

How to add multiple, independent HTTP interceptors to an Angular 4 application?

I tried to add them by extending the providers array with more than one inte

相关标签:
1条回答
  • 2021-01-30 08:48

    Http doesn't allow to have more than one custom implementation. But as @estus mentioned the Angular team has added a new HttpClient service recently (release 4.3) which supports multiple interceptors concept. You don't need to extend the HttpClient as you do with the old Http. You can provide an implementation for HTTP_INTERCEPTORS instead which can be an array with the 'multi: true' option:

    import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
    ...
    
    @NgModule({
      ...
      imports: [
        ... ,
        HttpClientModule
      ],
      providers: [
        ... ,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: InterceptorOne,
          multi: true,
        },
        {
          provide: HTTP_INTERCEPTORS,
          useClass: InterceptorTwo,
          multi: true,
        }
      ],
      ...
    })
    

    Interceptors:

    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
    ...
    
    @Injectable()
    export class InterceptorOne implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('InterceptorOne is working');
        return next.handle(req);
      }
    }
    
    @Injectable()
    export class InterceptorTwo implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('InterceptorTwo is working');
        return next.handle(req);
      }
    }
    

    This server call will print both interceptors' log messages:

    import {HttpClient} from '@angular/common/http';
    ...
    
    @Component({ ... })
    export class SomeComponent implements OnInit {
    
      constructor(private http: HttpClient) {}
    
      ngOnInit(): void {
        this.http.get('http://some_url').subscribe();
      }
    }
    
    0 讨论(0)
提交回复
热议问题