集中处理Angular 2 http错误

bal*_*ark 4 rxjs5 angular

我有一些代码处理一个处理添加令牌的类中的所有http访问.它返回一个Observable.我想捕获该类中的错误 - 特别是身份验证问题.我是一个RXjs初学者,无法弄清楚如何做到这一点仍然返回一个Observable.指向一些相当全面的rxJS 5文档(不是源代码!)的指针会很有用.

Thi*_*ier 9

catch在服务中执行HTTP调用时,您可以利用运算符:

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());
           });
}
Run Code Online (Sandbox Code Playgroud)

另一种方法可能是扩展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
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

并按如下所述注册:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);
Run Code Online (Sandbox Code Playgroud)

什么用真的取决于你的用例...

  • 我尝试了上面的例子但是收到了以下错误`错误TS2345:类型的参数'(res:any)=> void'不能分配给类型'的参数(错误:任何,源:Observable <Response>,catch:Observable <any>)=> Observable <any>'.类型'void'不能赋值为'Observable <any>'`.这发生在CustomHttp代码`return super.request(url,options).catch(res => {`. (5认同)