2015-06-16 44 views
2

我有一個網頁,其中有一堆用戶可以點擊的項目。點擊任何項目(取決於它的類型),將向服務器發送ajax請求,然後顯示更多項目。 如果請求導致錯誤,我想顯示它,然後讓用戶像以前一樣繼續點擊或與頁面交互。用flatMapLatest處理錯誤並重試

我的代碼看起來像這樣

$scope.$createObservableFunction("clickHandler") 
    .flatMapLatest(function (args) { 
     //send the ajax request to the server 
    }) 
    .retry() 
    .subscribe(function (data) { 
     //handle getting the data from the server 
    }) 

確切位置在哪裏我可以處理的錯誤呢?我希望發生錯誤,並且我總是希望重新訂閱源代碼,但我希望有機會處理該錯誤。

+1

什麼是'功能(參數)= {'? –

+0

對不起,我使用TypeScript並將'(args)=> {}'轉換爲'function(args){}',但忘記了'=':) – ahmelsayed

回答

3

訣竅是把你的錯誤引入數據:

$scope.$createObservableFunction("clickHandler") 
    .flatMapLatest(function (args) { 
     //send the ajax request to the server 
     var ajaxQuery = someObservable; 

     // turn the observable into 
     // a stream of eithers, which will 
     // either have a 'result' 
     // or an 'error' 
     // use .catch() to turn the error 
     // into a either with an error property 
     // use .map() to turn the success 
     // into a either with the result property 
     return ajaxQuery 
      .map(function (result) { 
       return { result: result }; 
      }) 
      .catch(function (error) { 
       return Rx.Observable.of({ error: error }); 
      }); 
    }) 
    .subscribe(function (data) { 
     if (data.error) { 
      // display data.error to user 
     } 
     else { 
      // display data.result to user 
     } 
    }) 

如果你的Ajax方法返回一個Promise,使用then鏈接:

$scope.$createObservableFunction("clickHandler") 
    .flatMapLatest(function (args) { 
     //send the ajax request to the server 
     var ajaxQuery = somePromise; 

     // turn the promise into 
     // a promise of eithers, which will 
     // either have a 'result' 
     // or an 'error' 
     return ajaxQuery 
      .then(function onSuccess(result) { 
       return { result: result }; 
      }, function onError (error) { 
       return { error: error }; 
      }); 
    }) 
    .subscribe(function (data) { 
     if (data.error) { 
      // display data.error to user 
     } 
     else { 
      // display data.result to user 
     } 
    }) 
+1

傳入'catch'的方法應返回'Observable' – paulpdaniels

+0

這正是我需要的。非常感謝。我花了很多時間閱讀了Rx中所有不同類型的錯誤處理方法,但無法親自體會到這一點。再次感謝! – ahmelsayed