标签:esc form 必须 功能 core 注入 实现 接口 lock
就要先导入 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 {}
要实现拦截器,就要实现一个实现了
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
这个模块,将会导致全局的被覆盖,所以懒加载模块无法使用全局的拦截。
// other.module.ts
@NgModule({
imports: [
BrowserModule,
// HttpClientModule 删除多余的模块,即可发现全局拦截生效
]
})
export class OtherModule {}
标签:esc form 必须 功能 core 注入 实现 接口 lock
原文地址:https://www.cnblogs.com/chenfengami/p/13231053.html