【问题标题】:Create angular promise with another value用另一个值创建 Angular Promise
【发布时间】:2017-11-07 21:54:13
【问题描述】:

我有一个返回一些数据的网络服务。为防止代码重复,我想将 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;
});

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

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

【问题讨论】:

    标签: angularjs promise angular-promise


    【解决方案1】:

    调用$http.post('/path/', {}) 返回一个promise,然后你调用then()。注意then() 也返回一个promise,所以你可以链接调用。因此,您的代码可能如下所示:

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

    【讨论】:

      【解决方案2】:

      您可以使用在$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;
      });
      

      【讨论】:

        猜你喜欢
        • 2017-06-22
        • 1970-01-01
        • 1970-01-01
        • 2019-09-17
        • 2019-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-18
        相关资源
        最近更新 更多