How to create interceptors in Angular2?

I am building my first larger application in Angular2, and I wonder how I can build something that will become an alternative to Angular1 interceptors? I dug on the Internet and found out that I can create a class that will be almost the same as the Http class. However, I have no idea how I can implement the two functions that interest me the most: catching errors from the request, adding a header to the entire request.

Any pointers are more than welcome!

+1
angular
source share
1 answer

You can create a class that extends 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 can intercept requests ...

Update for RC4

 bootstrap(AppComponent, [HTTP_PROVIDERS, { provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions), deps: [XHRBackend, RequestOptions] } ]); 
+3
source share

All Articles