1

I am building my first larger app in Angular2, and I am wondering how can I build something which will be an alternative to Angular1 interceptors? I was digging the Internet, and found out that I can create a class, which will be pretty much the same as Http class. However, I have no idea how I can implement two functionalities that I am the most interested in: intercepting errors from request, adding a header to all of the request.

Any pointers are more than welcome!

uksz
  • 18,239
  • 30
  • 94
  • 161

1 Answers1

3

You could create a class that extends the Http:

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

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

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    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]
  })
]);

This way you will be able to intercept requests...

Update for RC4

bootstrap(AppComponent, [HTTP_PROVIDERS,
    { provide: Http,
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
    }
]);
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Do you have any idea which class should I override to handle responses as well? – uksz Mar 14 '16 at 11:47
  • and btw, thanks for this answer - it works great; however the 'catch' part of it is not working. – uksz Mar 14 '16 at 11:48
  • 1
    You're welcome! Regarding the `catch` part, it depends on what you want to do. If you want to error to be thrown to the `subscribe`, you need to return in it `Observable.throw(...)`. Otherwise you can do some other stuff... – Thierry Templier Mar 14 '16 at 12:07
  • @uksz I updated my answer. The only thing is the way to configure the provider using the literal form... – Thierry Templier Aug 05 '16 at 21:24
  • @ThierryTemplier, is there a particular location I need to put the CustomHttp class in? Thanks – Artanis Zeratul Aug 01 '18 at 04:55