我正在Angular2中构建我的第一个更大的应用程序,我想知道如何构建一些可以替代Angular1拦截器的东西?我正在挖掘互联网,发现我可以创建一个类,它与Http类几乎相同。但是,我不知道如何实现我最感兴趣的两个功能:拦截请求中的错误,为所有请求添加标头。
任何指针都非常受欢迎!
答案 0 :(得分:3)
您可以创建一个扩展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
});
}
}
并按如下所述进行注册:
bootstrap(AppComponent, [HTTP_PROVIDERS,
new Provider(Http, {
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
})
]);
这样你就可以拦截请求......
RC4更新
bootstrap(AppComponent, [HTTP_PROVIDERS,
{ provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}
]);