In angularjs, we have http interceptor
$httpProvider.interceptors.push('myHttpInterceptor');
with which we can hook into all http calls, and show or hide loading bars, do logging, etc..
What is the equivalent in angular2?
In angularjs, we have http interceptor
$httpProvider.interceptors.push('myHttpInterceptor');
with which we can hook into all http calls, and show or hide loading bars, do logging, etc..
What is the equivalent in angular2?
Angular 4.3 now supports Http interceptor out-of-the-box. Check it out how to use them: https://ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors
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 callsFirst you could create a class that extends the
Http
:and register it as described below:
The
request
andrequestError
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 (likeflatMap
) of Observable.Finally for the
responseError
one, you need to call thecatch
operator on the target call. This way you will be notified when an error occurs in the response.This links could help you:
I have released interceptor with following node module. We was create this module for our internal purpose finally we released in npm package manager npm install angular2-resource-and-ajax-interceptor https://www.npmjs.com/package/angular2-resource-and-ajax-interceptor
update
The new
HttpClient
module introduced in Angular 4.3.0 supports interceptors https://github.com/angular/angular/compare/4.3.0-rc.0...4.3.0original
Angular2 doesn't have (yet) interceptors. You can instead extend
Http
,XHRBackend
,BaseRequestOptions
or any of the other involved classes (at least in TypeScript and Dart (don't know about plain JS).See also
There's an implementation for a Http @angular/core-like service in this repository: https://github.com/voliva/angular2-interceptors
You just declare the provider for that service on bootstrap, adding any interceptors you need, and it will be available for all the components.
As @squadwuschel pointed out, work is underway to get this functionality into @angular/http. This will be in the form of a new HttpClient API.
See https://github.com/angular/angular/pull/17143 for more details and current status.