如何,我想全局处理http错误(特别是状态401)。我知道我可以做那样的事情
getCompanies() {
return this.http.get('https://angular2.apispark.net/v1/companies/')
.map(res => res.json())
.catch(res => {
return Observable.throw(res.json());
});
如何在其他组件上获得此错误?
只是为了解释我想实现所有401错误将用户重定向到登录页面
答案 0 :(得分:8)
一种方法可能是扩展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]
})
]);
如果401级错误发生在此级别,您可以根据您在此CustomHttp类上注入的当前路由器将用户重定向到登录页面。