如何,我想全局处理http错误(特别是状态401).我知道我可以做那样的事
getCompanies() { return this.http.get('https://angular2.apispark.net/v1/companies/') .map(res => res.json()) .catch(res => { return Observable.throw(res.json()); });
如何在其他组件上获得此错误?
一种方法可以是扩展HTTP对象以拦截错误:
原文链接:https://www.f2er.com/angularjs/143603.html@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] }) ]);