rxjs5 - Handling Angular 2 http errors centrally -
i have code handles http access in class handles adding tokens. returns observable. want catch errors in class - in particular authentication problems. rxjs beginner , can't figure out how , still return observable. pointer comprehensive rxjs 5 documentation (that isn't source code!) useful.
you can leverage catch
operator when executing http call within service:
getcompanies() { return this.http.get('https://angular2.apispark.net/v1/companies/') .map(res => res.json()) .catch(res => { // // throw error, use observable.throw // return observable.throw(res.json()); }); }
another approach extend http object 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 => { // }); } get(url: string, options?: requestoptionsargs): observable<response> { console.log('get...'); return super.get(url, options).catch(res => { // }); } }
and register described below:
bootstrap(appcomponent, [http_providers, new provider(http, { usefactory: (backend: xhrbackend, defaultoptions: requestoptions) => new customhttp(backend, defaultoptions), deps: [xhrbackend, requestoptions] }) ]);
what use depends on use case...
Comments
Post a Comment