Handling Angular 2 http errors centrally

£可爱£侵袭症+ 提交于 2019-12-10 15:43:08

问题


I have some code that handles all http access in a class that handles adding tokens. It returns an Observable. I want to catch errors in that class - in particular authentication problems. I am an RXjs beginner and can't figure out how to do this and still return an Observable. A pointer to some fairly comprehensive rxJS 5 documentation (that isn't source code!) would be useful.


回答1:


You can leverage the catch operator when executing an HTTP call within a service:

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());
           });
}

Another approach could be to extend the HTTP object to intercept errors:

@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
    });
  }
}

and register it as described below:

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

What to use really depends on your use case...



来源:https://stackoverflow.com/questions/35274523/handling-angular-2-http-errors-centrally

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!