使用另一个值创建 angular 个承诺

Create angular promise with another value

我有一个 Web 服务,其中 return 有一些数据。为了防止代码重复,我想将 http 请求调用移动到 angular 服务:

angular.module('abc', [])
    .factory('def', function () {
        return {
            getData: function () {
                return $http.post('/path/', {});
            }
        };
    });

一切都很好,但必要的数据在复杂的对象中,每次都必须写:

def.getData().then(function (response) {
    scope.obj = response.data.qwe.rty.xyz;
});

return 承诺的最简单方法是什么,它将 response.data.qwe.rty.xyz 的值直接发送到 successCallback?我可以这样写:

def.getData().then(function (obj) {
    scope.obj = obj;
});

调用 $http.post('/path/', {}) returns 您随后调用 then() 的承诺。请注意 then() 也是 returns 一个承诺,因此您可以链接调用。因此,您的代码可能如下所示:

angular.module('abc', [])
    .factory('def', function () {
        return {
            getData: function () {
                return $http.post('/path/', {})
                        .then(function(response) {
                            return response.data.qwe.rty.xyz;
                        });
            }
        };
    });

您可以使用 $q 提供程序中实现的延迟行为

像这样:

angular.module('abc', [])
.factory('def', function ($q) {

    return {
        getData: function () {
             var def = $q.defer
             $http.post('/path/', {}).then(function(response){
               def.resolve(response.data.qwe.rty.xyz)
             });
            return def.promise; 
        }
    };
});

并在您的控制器中使用它,例如:

def.getData().then(function (response) {
 scope.obj = response;
});