问题描述
我正在Angular2中构建我的第一个更大的应用程序,我想知道如何构建可以替代Angular1拦截器的东西?我正在研究Internet,发现可以创建一个类,该类与Http类几乎相同.但是,我不知道如何实现我最感兴趣的两个功能:拦截请求中的错误,向所有请求添加标头.
I am building my first larger app in Angular2, and I am wondering how can I build something which will be an alternative to Angular1 interceptors? I was digging the Internet, and found out that I can create a class, which will be pretty much the same as Http class. However, I have no idea how I can implement two functionalities that I am the most interested in: intercepting errors from request, adding a header to all of the request.
欢迎任何指针!
推荐答案
您可以创建一个扩展Http
的类:
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]
})
]);
这样,您将能够拦截请求...
This way you will be able to intercept requests...
针对RC4的更新
bootstrap(AppComponent, [HTTP_PROVIDERS,
{ provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}
]);
这篇关于如何在Angular2中创建拦截器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!