集中处理Angular 2 http错误 [英] Handling Angular 2 http errors centrally
问题描述
我有一些代码可以处理添加令牌的类中的所有http访问.它返回一个Observable.我想捕获该类中的错误-特别是身份验证问题.我是RXjs初学者,无法弄清楚该怎么做,仍然返回一个Observable.指向一些相当全面的rxJS 5文档(不是源代码!)的指针会很有用.
I have some code that handles all http access in a class that handles adding tokens. It returns an Observable. I want to catch errors in that class - in particular authentication problems. I am an RXjs beginner and can't figure out how to do this and still return an Observable. A pointer to some fairly comprehensive rxJS 5 documentation (that isn't source code!) would be useful.
推荐答案
在服务中执行HTTP调用时,可以利用 catch
运算符:
You can leverage the catch
operator when executing an HTTP call within a service:
getCompanies() {
return this.http.get('https://angular2.apispark.net/v1/companies/')
.map(res => res.json())
.catch(res => {
// do something
// To throw another error, use Observable.throw
// return Observable.throw(res.json());
});
}
另一种方法可能是扩展HTTP对象以拦截错误:
Another 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]
})
]);
使用什么真的取决于您的用例...
What to use really depends on your use case...
这篇关于集中处理Angular 2 http错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!