如何在引导程序中将自定义拦截器添加到 Angular 4 应用程序
我制作了一个基本的拦截器来最终设置一个身份验证令牌。
我需要帮助将拦截器添加到核心应用程序模块。
这是我的拦截器代码(目前非常基本):
import { Injectable } from "@angular/core";
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers } from "@angular/http";
import { Observable } from "rxjs/Rx";
@Injectable();
export class CommonInterceptor implements HttpInterceptor {
className: string;
constructor(private logger: Logger) {
this.className = "CommonInterceptor";
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
return next.handle(req).do(event => {
console.log("Interceptor");
if (event.type === HttpEventType.Response) {
if (this.logger.isDebugEnabled()) {
const elapsed = Date.now() - started;
this.logger.debug(`${this.className}: Request for ${req.urlWithParams} took ${elapsed} ms.`);
}
}
});
}
};
这是我的应用程序模块(目前非常基本的应用程序):
import { NgModule } from "@angular/core";
import { routes } from "./app.routes";
import { BrowserModule } from "@angular/platform-browser";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { FormsModule} from "@angular/forms";
import { APP_BASE_HREF, CommonModule, } from "@angular/common";
import { RouterModule } from "@angular/router";
import { HttpModule, HTTP_INTERCEPTORS } from "@angular/http";
import { AppComponent } from "./app.component";
import { HomeModule } from "./components/home/home.module";
import { CommonInterceptor } from "./interceptor";
@NgModule({
imports: [BrowserModule, FormsModule, RouterModule, CommonModule, HttpModule, RouterModule.forRoot(routes),
HomeModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CommonInterceptor,
multi: true
}
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
我想将我的 CommonInterceptor 添加到应用程序模块中。
我怎么做?