Vikram Babu Nagineni Vikram Babu Nagineni - 1 year ago 112
HTTP Question

What is httpinterceptor equivalent in angular2?

In angularjs, we have http interceptor


with which we can hook into all http calls, and show or hide loading bars, do logging, etc..

What is the equivalent in angular2?

Answer Source

As @G√ľnter pointed it out, there is no way to register interceptors. You need to extend the Http class and put your interception processing around HTTP calls

First you could create a class that extends the Http:

export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options).catch(res => {
      // do something

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(url, options).catch(res => {
      // do something

and register it as described below:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]

The request and requestError kinds could be added before calling the target methods.

For the response one, you need to plug some asynchronous processing into the existing processing chain. This depends on your need but you can use operators (like flatMap) of Observable.

Finally for the responseError one, you need to call the catch operator on the target call. This way you will be notified when an error occurs in the response.

This links could help you:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download