2016-08-03 21 views
1

我是RxJs和Angular2的新手,我正在努力處理錯誤。我已經看到一些示例使用onNext,onError和onCompleted事件(例如here,但我看到的所有Angular2 http示例似乎只使用.catch和.map方法,但我不確定這是如何涉及的。到OnNext /的OnError/OnCompleted模型,我的代碼工作從here):RxJ可以鏈接Angular2 Http響應是有條件的嗎?

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要麼/或? (即只有在http請求成功時,纔會運行.map),但我不確定這是否可能,然後通過閱讀here這個帖子,看起來他們可能會說根據this fix,如果HTTP代碼是< 200或> 300 ...,則地圖方法將自動跳過?但是,這不是我在實踐中觀察到的角2.0.0-rc.4 ...

非常感謝您的任何幫助!

回答

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); 
    });