AngularJS,在服务中使用承诺

AngularJS, using a promise within a service

我有一个来自某个项目的 MVP 的 "really fat controller" 控制器,我想将其重构为更加模块化和分隔化的代码。

目前我的控制器中有一个功能:

  1. $HTTP 调用 API
  2. for循环和switch语句处理返回的数据
  3. 将其保存到范围

我想将其移至服务中。到目前为止我有这个:

angular.module('myApp.services', [])
.service('apiService', ['$http', 'webapiBase', function($http, webapiBase) {
  this.getData = function(){
    $http.get(webapiBase + '/api/getData').then(function(res){
      var obj = res.data;
      // Processing stuff
      return obj;
    }, function(err){
      return false;
    })
  }
}]);

在我的控制器中,当此服务 returns 其数据时,我需要 运行 回调,例如:

// In my Service:
this.getData = function(cb){
    $http.get(webapiBase + '/api/getData').then(function(res){
       var obj = res.data; 
       cb(obj);
    }, function(err){
       cb(false);
    })
  }

// In my controller
apiService.getData(function(data){
    $scope.data = data;
    // Do other stuff here
})   

不过这个感觉有点weird/non-'Angular'.

是否有更多 "Angular" 的方法来实现这一点,或许在使用 $q 时?

您只需要对您的服务做一个小的修改

  this.getData = function(){
    return $http.get(webapiBase + '/api/getData').then(function(res){
      // Processing stuff
      return object;
    }, function(err){
      return false;
    })
  }

Return 直接 $http.get 的 promise 对象。然后在你的控制器中

apiService.getData().then(function(data){
    $scope.data = data;
    // Do other stuff here
})

编辑

如果您真的不想重用 $http 创建的 promise 对象,您可以快速创建自己的对象。

this.getData = function() {
    var deferred = $q.defer();

    $http.get(webapiBase + '/api/getData').then(function(res){
      // Processing stuff
      deferred.resolve(object);
    }, function(err){
      deferred.reject('error');
    });

    return deferred.promise;
}

您可以使用 $q 来实现您想要的。

// Your service
angular.module('myApp.services', [])
.service('apiService', ['$http', 'webapiBase', function($http, webapiBase) {
  this.getData = function() {
    var deferred = $q.defer();
    $http.get(webapiBase + '/api/getData').then(
        function (res) {
            // Do something with res.data
            deferred.resolve(res.data);
        },
        function(res){
            deferred.reject();
        }
    );
    return deferred.promise;
  }
}]);

然后在你的控制器中使用 $q promise 并响应它:

// Your controller
apiService.getData().then(function(data) {
    $scope.data = data;
    // Do other stuff here
});

这就是 Angular 方式,使用 $q 的承诺。