是否可以将 Angular2 Http 响应的 RxJs 链接设置为有条件的?

Can RxJs chaining for Angular2 Http responses be made conditional?

我是 RxJs 和 Angular2 的新手,我正在尝试正确处理错误。我看过一些带有 onNext、onError 和 onCompleted 事件的 Observable 示例(例如 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));
    });

我最初只想让第一个 .catch 和 .map 是 either/or? (即 .map 仅在 http 请求成功时运行),但我不确定这是否可能,然后通过阅读 post where it seems like they may be saying that per this fix,map 方法使它变得更加复杂如果 HTTP 代码 <200 或 >300 会自动跳过...?然而,这不是我在 angular 2.0.0-rc.4...

实践中观察到的

非常感谢您的帮助!

catch 视为典型的 trycatch 代码。对于一个 observable,所有的操作都是 运行 的顺序,就好像它们在 try 块中一样。如果有错误,那么处理会跳转到第一个catch.

所以,如果你只想 运行 map 成功,那么你只需将它 放在 之前 catch:

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