首页 文章

RxJs链接Angular2 Http响应可以有条件吗?

提问于
浏览
1

我'm new to RxJs and Angular2, and I'我试图正确处理错误 . 我已经看到了Observables的一些例子,它们有onNext,onError和onCompleted事件(例如here,但是我看到的所有Angular2 http示例似乎只是使用.catch和.map方法,而我'm not sure how that relates to the OnNext/OnError/OnCompleted model. I' m使用的代码来自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是/或? (即.map仅在http请求成功时才会运行),但我甚至可以使用'm not sure if that',然后通过我阅读帖子here进一步复杂化,似乎他们可能会说this fix, Map 方法将会如果HTTP代码<200或> 300 ......会自动跳过?然而,在实践中观察角度为2.0.0-rc.4 ......

非常感谢您的帮助!

1 回答

  • 0

    可以认为 catch 与典型的 trycatch 代码相似 . 对于可观察的,所有操作都将按顺序运行,就好像它们位于 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);
        });
    

相关问题