基于安德鲁的回答。
如果您想在此 httpClient 管道中使用拦截器,请从 angular repo http/src/interceptor.ts 和 http/src/module.ts 添加两个重新定义的类:
class HttpInterceptorHandler implements HttpHandler {
constructor(private next: HttpHandler, private interceptor: HttpInterceptor) {}
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
return this.interceptor.intercept(req, this.next);
}
}
class HttpInterceptingHandler implements HttpHandler {
private chain: HttpHandler|null = null;
private httpBackend:HttpHandler;
constructor(private injector: Injector) {
this.httpBackend = new HttpXhrBackend({ build: () => new XMLHttpRequest });
}
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
if (this.chain === null) {
const interceptors = this.injector.get(HTTP_INTERCEPTORS, []);
this.chain = interceptors.reduceRight((next, interceptor) => new HttpInterceptorHandler(next,interceptor),this.httpBackend);
}
return this.chain.handle(req);
}
}
拦截器需要没有@Injectable 装饰器:
class HttpIntersept implements HttpInterceptor{
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(req.urlWithParams);
return next.handle(req)
}
}
就像安德鲁所说的那样
const injector = Injector.create({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpIntersept, multi: true, deps: []},
{ provide: HTTP_INTERCEPTORS, useClass: HttpIntersept2, multi: true, deps: []},
{ provide: HttpHandler, useClass:HttpInterceptingHandler,deps [Injector,HTTP_INTERCEPTORS]},
{ provide: HttpClient, deps: [HttpHandler] }
],
});