How to add a custom interceptor to angular 4 app in bootstrap
I've made a basic interceptor to eventually set a auth token.
I need help adding the interceptor to the core app module.
This is my interceptor code (very basic at the moment):
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.`);
}
}
});
}
};
This is my app module (very basic app at moment):
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 { }
I want to add my CommonInterceptor to the app module.
How do I do that?
You need not add it to you bootstrap array to use it.
add
to your providers array.
Also an ideal interceptor would look like, I couldn't understand your version:
Edit
Added the imports