gpt4 book ai didi

angular - 向 Angular 应用程序添加多个 HTTP 拦截器

转载 作者:太空狗 更新时间:2023-10-29 16:45:58 27 4
gpt4 key购买 nike

如何向 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,
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
new Interceptor2(xhrBackend, requestOptions),
deps: [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,
},
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorTwo,
multi: true,
}
],
...
})

拦截器:

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

关于angular - 向 Angular 应用程序添加多个 HTTP 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633102/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com