问题描述
在angularjs中,我们有http拦截器
In angularjs, we have http interceptor
$httpProvider.interceptors.push('myHttpInterceptor');
通过它我们可以连接到所有的 http 调用,并显示或隐藏加载条,进行日志记录等.
with which we can hook into all http calls, and show or hide loading bars, do logging, etc..
angular2 中的等价物是什么?
What is the equivalent in angular2?
推荐答案
正如@Günter 所指出的,没有办法注册拦截器.您需要扩展 Http
类并将您的拦截处理放在 HTTP 调用周围
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 calls
首先你可以创建一个扩展 Http
的类:
First you could create a class that extends the 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]
})
]);
request
和 requestError
类型可以在调用目标方法之前添加.
The request
and requestError
kinds could be added before calling the target methods.
对于response
,你需要将一些异步处理插入到现有的处理链中.这取决于您的需要,但您可以使用 Observable 的运算符(如 flatMap
).
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 (like flatMap
) of Observable.
最后对于 responseError
一个,你需要在目标调用上调用 catch
操作符.这样,您将在响应中出现错误时收到通知.
Finally for the responseError
one, you need to call the catch
operator on the target call. This way you will be notified when an error occurs in the response.
此链接可以帮助您:
这篇关于angular2 中的 httpinterceptor 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!