向Angular Application添加多个HTTP拦截器
发布时间:2020-12-17 08:02:27 所属栏目:安全 来源:网络整理
导读:如何向Angular 4应用程序添加多个独立的HTTP拦截器? 我尝试通过使用多个拦截器扩展providers数组来添加它们。但实际上只执行了最后一个,Interceptor1被忽略了。 @NgModule({ declarations: [ /* ... */ ],imports: [ /* ... */ HttpModule ],providers: [
如何向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(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |