admin管理员组文章数量:1435859
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.
本文标签: javascriptAngular 2 (Ionic 2) intercept ajax requestsStack Overflow
版权声明:本文标题:javascript - Angular 2 (Ionic 2): intercept ajax requests - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745675191a2669807.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论