2

I'm new to RxJs and Angular2, and I'm trying to properly handle errors. I've seen some examples with Observables that have onNext, onError and onCompleted events (e.g. here, but all of the Angular2 http examples that I see seem to just use .catch and .map methods, and I'm not sure how that relates to the OnNext/OnError/OnCompleted model. I'm working with the code from here):

let stream = this.http.request(options.url, options)
     .catch(error: any) => {
        this.errorsSubject.next(error);
        return Observable.throw(error);
     })
    .map(this.unwrapHttpValue)
    .catch((error: any) => {
            return Observable.throw(this.unwrapHttpError(error));
    });

I initially wanted to just make it so that the first .catch and the .map are either/or? (i.e. the .map only runs if the http request is successful), but I'm not sure if that's even possible, and then it was further complicated by my reading the post here where it seems like they may be saying that per this fix, the map method will automatically be skipped if the HTTP code is <200 or >300...? However, that isn't what I'm observing in practice with angular 2.0.0-rc.4...

Many thanks for any assistance!

1 Answer 1

0

Think of catch being like typical try and catch code. For an observable, all of the operations will be run in order as if they were in a try block. If there is an error, then processing will jump down to the first catch.

So, if you only want to run the map on success, then you just put it before the catch:

let stream = this.http.request(options.url, options)
    .map(this.unwrapHttpValue)
    .catch(error: any) => {
       this.errorsSubject.next(error);
       return Observable.throw(error);
    });
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.