Search code examples
angularangular2-http

Append header to all Http Requests -> Angular2


I need the equivalent of the interceptor in Angular 1.x. I found a lot of solutions in old questions, but apparently they are not working anymore!

Can you provide a solution that works with the latest release of Angular 2?


Solution

  • You can override Angular's Http class, add headers there and then provide CustomHttp class in your modules:

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Rx';
    import { RequestOptionsArgs, RequestOptions, ConnectionBackend, Http, Request, Response, Headers } from "@angular/http";
    
    @Injectable()
    export class CustomHttp extends Http {
    
    headers: Headers = new Headers({ 'Something': 'Something' });
    options1: RequestOptions = new RequestOptions({ headers: this.headers });
    
    constructor(backend: ConnectionBackend,
        defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }
    
    get(url: string, options?: RequestOptionsArgs) {
        console.log('Custom get...');
        return super.get(url, this.options1).catch(err => {
            console.log(err);
        });
    }
    }
    

    You need to do the same for post, put, delete etc. And in your module:

    { provide: Http, 
        useFactory: (
            backend: XHRBackend,
            defaultOptions: RequestOptions) =>
            new CustomHttp(backend, defaultOptions),
        deps: [XHRBackend, RequestOptions]
    }