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?
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?
Share Improve this question asked Mar 4, 2016 at 17:34 Christian BenselerChristian Benseler 8,0759 gold badges42 silver badges73 bronze badges1 Answer
Reset to default 6An approach could be to extend the HTTP
object to intercept calls:
@Injectable()
export class CustomHttp extends Http {
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]
})
]);
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745675191a4639642.html
评论列表(0条)