javascript angularjs 处理 $resource $promise 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25070690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:51:43  来源:igfitidea点击:

angularjs handling $resource $promise errors

javascriptangularjsangular-resourceangular-promise

提问by helloMeWorld

Could somebody help me figure out how to return hard-coded data in my AngularJS factory if there is an error connecting to my API. My hard-coded data are located in another factory called "dataFactory". Appreciate the assistance.

如果连接到我的 API 时出现错误,有人能帮我弄清楚如何在我的 AngularJS 工厂中返回硬编码数据。我的硬编码数据位于另一个名为“dataFactory”的工厂中。感谢帮助。

service.factory("ScheduleFactory", ['$http', '$resource', '$q', 'dataFactory', function($http, $resource, $q, dataFactory) {
        var objFactory = {};

        objFactory.getDaysOfWeek = function(includeWeekends) {
            var days = [];
            var API  = $resource(restURL + '/daysOfWeek/');

            API.query()
                .$promise
                    .then(function(data) {
                        isEmpty = (data.length === 0);

                        if (!isEmpty) {
                            days    = data;
                        };
                    })
                    .catch(function(error) {
                        console.log("rejected " + JSON.stringify(error));

                        var data    = null;
                        days    = dataFactory.daysOfWeek;

                        console.log(days.length); // returns 5
                    });


            console.log("after promise " + days.length);  // returns 'after promise 0'

            return days;
        };

My dataFactory is defined as follows:

我的数据工厂定义如下:

dataApp.factory("dataFactory", function() {
    objDataFactory  = {};

    objDataFactory.daysOfWeek = [
        {   dayName:        'Monday'
            , dayAbbrev:    'Mon'
            , index:        1
            , isSelected:   false
            , isWeekday:    true    }
        , { dayName:        'Tuesday'
             , dayAbbrev:   'Tue'
             , index:       2
             , isSelected:  false
             , isWeekday:   true    }
        , { dayName:        'Wednesday'
             , dayAbbrev:   'Wed'
             , index:       3
             , isSelected:  false
             , isWeekday:   true    }
        , { dayName:        'Thursday'
             , dayAbbrev:   'Thu'
             , index:       4
             , isSelected:  false
             , isWeekday:   true    }
        , { dayName:        'Friday'
             , dayAbbrev:   'Fri'
             , index:       5
             , isSelected:  false
             , isWeekday:   true    }
    ];

    return objDataFactory;
});

回答by MBielski

I'd like to think this is what you are looking for:

我想这就是你要找的:

service.factory("ScheduleFactory", ['$http', '$resource', '$q', 'dataFactory', function($http, $resource, $q, dataFactory) {
     var objFactory = {};

     objFactory.getDaysOfWeek = function(includeWeekends) {
          var API  = $resource(restURL + '/daysOfWeek/'), defObj = $q.defer();

          var daysQuery = API.query();
          daysQuery.$promise.then(function(data) {
                    //you can add anything else you want inside this function
                    defObj.resolve(data);
               }, function(error) {
                    //you can add anything else you want inside this function
                    defObj.resolve(dataFactory.daysOfWeek);
               });

            return defObj.promise;
        };

I've skipped any data formatting and assignment details because you're liable to change them anyway. By wrapping your API query in an extra promise you gain the ability to manipulate what is returned. If your API can be reached, you return the data from it in the resolution of your outer promise. Otherwise, you return your hard-coded data from your other service in the resolution of your outer promise.

我跳过了任何数据格式和分配细节,因为无论如何你都有可能改变它们。通过将您的 API 查询包装在一个额外的承诺中,您可以获得操作返回内容的能力。如果您的 API 可以访问,您可以在外部承诺的解析中从中返回数据。否则,您将在解决外部承诺时从其他服务返回硬编码数据。

回答by Shomz

No catch block, use a regular error callback function:

没有 catch 块,使用常规的错误回调函数:

   API.query()
        .$promise
            .then(function(data) {
                    isEmpty = (data.length === 0);

                    if (!isEmpty) {
                        days    = data;
                 },
                 function(error) { // removed catch here
                    console.log("rejected " + JSON.stringify(error));

                    var data    = null;
                    days    = dataFactory.daysOfWeek;

                    console.log(days.length); // returns 5
                ...

See in the docs:

请参阅文档

then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.

then(successCallback, errorCallback, notifyCallback) – 无论承诺何时被解决或将被解决或拒绝,一旦结果可用,就会异步调用成功或错误回调之一。使用单个参数调用回调:结果或拒绝原因。此外,在承诺被解决或拒绝之前,通知回调可以被调用零次或多次以提供进度指示。