How to add a custom interceptor to angular 4 app in bootstrap

1.3k views Asked by At

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?

2

There are 2 answers

7
Sumit Agarwal On

You need not add it to you bootstrap array to use it.

add

{
        provide: HTTP_INTERCEPTORS,
        useClass: CustomHttp,
        multi: true
},

to your providers array.

Also an ideal interceptor would look like, I couldn't understand your version:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import {Logger} from "../../logger/logger";
import 'rxjs/add/operator/do';

 @Injectable()
export class CommonInterceptor implements HttpInterceptor {

    className: string;
/**
 *
 * @param {Logger} logger
 */
constructor(private logger: Logger) {
    this.className = "CommonInterceptor";
}


/**
 *
 * @param {HttpRequest<any>} req
 * @param {HttpHandler} next
 * @returns {Observable<HttpEvent<any>>}
 */
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();
    return next.handle(req).do(event => {
        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.`);
            }
        }
    });

}
}

Edit

Added the imports

0
Deyvison Souto On

in your app.module.ts `

providers: [
     AccountService,
     AuthJwtService,
      AuthService,
     LocalStorageService,
     SessionStorageService,
     AuthGuardService,
//add this code bellow
     {
       provide: Http,
       useFactory: HttpIntercepter,
       deps: [XHRBackend, RequestOptions]
     }
   ]

`

In you can add simple this function in your customhttp file

export function HttpIntercepter(backend: XHRBackend, options: RequestOptions) {
   return new CustomHttp(backend, options);
 }