Angular 2 - 如何全局获取Observable.throw

时间:2016-02-16 17:52:11

标签: angular rxjs

如何,我想全局处理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错误将用户重定向到登录页面

1 个答案:

答案 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类上注入的当前路由器将用户重定向到登录页面。