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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With