Http
不允许有多个自定义实现。但是正如@estus提到的,Angular团队增加了一个新的
HttpClient
最近的服务(4.3版),支持多拦截器概念。您不需要扩展
HttpClient
就像你对待老人一样
Http
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();
}
}