2

ユーザーがクリックできるアイテムがたくさんある Web ページがあります。アイテムをクリックすると、そのタイプに応じて ajax リクエストがサーバーに送信され、さらにアイテムが表示されます。リクエストがエラーになった場合は、それを表示して、ユーザーが以前と同じようにページをクリックしたり操作したりできるようにしたいと考えています。

私のコードは次のようになります

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

エラーケースはどこで正確に処理できますか? エラーが発生することを予期しており、常にソースを再サブスクライブしたいと考えていますが、そのエラーを処理する機会が必要です。

4

1 に答える 1

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
         }
    })
于 2015-06-16T21:34:58.330 に答える