使用HTTP拦截器时必须导入HttpClientModule
全局AppModule导入HttpClientModule
就要先导入 Angular 的
HttpClientModule
。大多数应用都会在根模块AppModule
中导入它。
// app.module.ts
import { NgModule } from ‘@angular/core‘;
import { BrowserModule } from ‘@angular/platform-browser‘;
import { HttpClientModule } from ‘@angular/common/http‘;
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
使用HTTP拦截器
要实现拦截器,就要实现一个实现了
HttpInterceptor
接口中的intercept()
方法的类。
// app.interceptor.ts
import { Injectable } from ‘@angular/core‘;
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from ‘@angular/common/http‘;
import { Observable } from ‘rxjs‘;
/** Pass untouched request through to the next request handler. */
@Injectable()
export class Interceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(req);
}
}
注入拦截器
// app.module.ts
import { NgModule } from ‘@angular/core‘;
import { BrowserModule } from ‘@angular/platform-browser‘;
import { HttpClientModule } from ‘@angular/common/http‘;
import { HTTP_INTERCEPTORS } from ‘@angular/common/http‘;
// import class Interceptor
import { Interceptor } from ‘./services/app.interceptor‘;
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: Interceptor,
multi: true,
},
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
懒加载模块无法触发拦截器的问题
因为使用拦截器是要在模块中导入HttpClientModule
才可以使用对应里面的一些功能,因此如果在懒加载模块中使用HttpClientModule
这个模块,将会导致全局的被覆盖,所以懒加载模块无法使用全局的拦截。
删除多余的HttpClientModule
// other.module.ts
@NgModule({
imports: [
BrowserModule,
// HttpClientModule 删除多余的模块,即可发现全局拦截生效
]
})
export class OtherModule {}