在我的Angular 2项目中,我从返回Observable的服务中进行API调用。调用代码然后订阅这个可观察的。例如:
原文链接:https://www.f2er.com/angularjs/145129.htmlgetCampaigns(): Observable<Campaign[]> { return this.http.get('/campaigns').map(res => res.json()); }
假设服务器返回401.如何在全局范围内捕获此错误并重定向到登录页面/组件?
谢谢。
这里是我到目前为止:
// boot.ts
import {Http,XHRBackend,RequestOptions} from 'angular2/http'; import {CustomHttp} from './customhttp'; bootstrap(AppComponent,[HTTP_PROVIDERS,ROUTER_PROVIDERS,new Provider(Http,{ useFactory: (backend: XHRBackend,defaultOptions: RequestOptions) => new CustomHttp(backend,defaultOptions),deps: [XHRBackend,RequestOptions] }) ]);
// customhttp.ts
import {Http,ConnectionBackend,Request,RequestOptions,RequestOptionsArgs,Response} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; @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); } get(url: string,options?: RequestOptionsArgs): Observable<Response> { console.log('get...'); return super.get(url,options); } }