角2 - 如何获得Observable.throw全球 [英] Angular 2 - How to get Observable.throw globally
本文介绍了角2 - 如何获得Observable.throw全球的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么样,要处理HTTP错误(特殊地位401)全球。我知道我可以做这样的事情。
How, I want to handle http errors (specially status 401) globally. I know I can do something like that
getCompanies() {
return this.http.get('https://angular2.apispark.net/v1/companies/')
.map(res => res.json())
.catch(res => {
return Observable.throw(res.json());
});
我
怎样才能得到这个错误的另一个组成部分?
How can I get this error on another component?
只是为了解释我想实现所有401误差修改将用户重定向到登录页面
Just to explain I want to implement that all 401 erros redirect the user to login page
推荐答案
方式可能是延长HTTP对象拦截错误:
An approach could be to extend the HTTP object to intercept errors:
@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]
})
]);
如果401错误,因为这个级别的发生,你可以将用户重定向到登录页面根据您在本CustomHttp注入类在当前路由器上。
If 401 errors occur as this level, you could redirect the user to login page based on the current router you injected on this CustomHttp class.
这篇关于角2 - 如何获得Observable.throw全球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文