With Angular 1.x is possible to intercept all ajax requests with some code like:
$httpProvider.interceptors.push('interceptRequests');
...
var app_services = angular.module('app.services', []);
app_services.factory('interceptRequests', [function () {
var authInterceptorServiceFactory = {};
var _request = function (config) {
//do something here
};
var _responseError = function (rejection) {
//do something here
}
authInterceptorServiceFactory.request = _request;
authInterceptorServiceFactory.responseError = _responseError;
return authInterceptorServiceFactory;
}]);
Is there anything similar (or out-of-the-box) in Angular 2?
See this link about ionic2 interceptors: http://roblouie.com/article/354/http-interceptor-in-angular-2/
1 - Override Http standard class
2 - Register provider
3 - And just use Http class, because the Custom Http Interceptor instance is injected automatically.
An approach could be to extend the
HTTP
object to intercept calls:and register it as described below:
You can leverage for example the
catch
operator to catch errors and handle them globally...See this plunkr: https://plnkr.co/edit/ukcJRuZ7QKlV73jiUDd1?p=preview.