2

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?

1
  • 1
    Have a look: 41998690 Commented Mar 24, 2017 at 14:57

1 Answer 1

2

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]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, thanks man! I only needed the last part (how to declare the new service in the NgModule), and it worked immediatly!
@Nano Glad I could be of assistance, please consider marking my answer as accepted if it helped you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.