向Angular Application添加多个HTTP拦截器

前端之家收集整理的这篇文章主要介绍了向Angular Application添加多个HTTP拦截器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何向Angular 4应用程序添加多个独立的HTTP拦截器?

我尝试通过使用多个拦截器扩展providers数组来添加它们。但实际上只执行了最后一个,Interceptor1被忽略了。

@NgModule({
  declarations: [ /* ... */ ],imports: [ /* ... */ HttpModule ],providers: [
    {
      provide: Http,useFactory: (xhrBackend: XHRBackend,requestOptions: RequestOptions) =>
        new Interceptor1(xhrBackend,requestOptions),deps: [XHRBackend,RequestOptions],},{
      provide: Http,requestOptions: RequestOptions) =>
        new Interceptor2(xhrBackend,RequestOptions]
    },],bootstrap: [AppComponent]
})
export class AppModule {}

我显然可以将它们组合成一个Interceptor类,这应该可行。但是,我想避免这种情况,因为这些拦截器具有完全不同的目的(一个用于错误处理,一个用于显示加载指示符)。

那么如何添加多个拦截器呢?

Http不允许有多个自定义实现。但正如@estus提到的那样,Angular团队最近添加了一个新的 HttpClient服务(版本4.3),它支持多个拦截器概念。您不需要像使用旧的Http那样扩展HttpClient。您可以为HTTP_INTERCEPTORS提供一个实现,它可以是一个带有’multi:true’选项的数组:
import {HTTP_INTERCEPTORS,HttpClientModule} from '@angular/common/http';
...

@NgModule({
  ...
  imports: [
    ...,HttpClientModule
  ],providers: [
    ...,{
      provide: HTTP_INTERCEPTORS,useClass: InterceptorOne,multi: true,useClass: InterceptorTwo,}
  ],...
})

拦截器:

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);
  }
}

此服务器调用将打印两个拦截器的日志消息:

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();
  }
}
原文链接:https://www.f2er.com/angularjs/143928.html

猜你在找的Angularjs相关文章