2

我有一个网页,其中有一堆用户可以点击的项目。单击任何项​​目,具体取决于它的类型,将向服务器发送一个 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 方法返回 a 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 回答