AngularJS承诺没有回调?

时间:2015-01-02 13:08:24

标签: javascript ajax angularjs asynchronous angular-promise

通常当我得到一些数据异步时,我会像

那样做
var promise = $http.get('/api/v1/movies/avengers');

promise.then(
  function(payload) {
    $scope.movieContent = payload;
  });

事实上这种情况非常普遍 - 我发送了一些请求,当它准备就绪时,我会把它归结为一切变量/道具。但每次它都需要进行回调,即使回调总是相同的。

有没有办法像

那样做
$scope.movieContent = $http.get('/api/v1/movies/avengers'); //updates to real value when request is done

或者

updateWhenReady($scope.movieContent , '/api/v1/movies/avengers');

这不是什么大不了的事,但是在我看来,如果使用了很多东西会有所不同。

3 个答案:

答案 0 :(得分:1)

您可以设计服务,使其返回空引用,并在服务调用成功返回时自行填充。使用angular.copy保留引用:

<强>服务

app.factory('avengersService', function($http) {
   return  {
      getAvengers: function() {
         var avengers = [];
         avengers.$promise = $http.get('/api/v1/movies/avengers').then(function(result) {
             angular.copy(result.data, avengers);
             return result;
         });
         return avengers;
      }
   }
});

<强>控制器

app.controller('ctrl', function($scope, avengersService) {
    $scope.movieContent = avengersService.getAvengers();

    // or call the promise version
    avengersService.getAvengers().$promise.then(function(result) {
         $scope.movieContent = result.data;
    });

});

答案 1 :(得分:0)

您可以在函数中包装异步调用:

function load(cb, model){
        cb.then(function(payload){
            model = payload;
        });
    }

*但我不建议你这样做。通常,您希望在回调函数中执行特定任务(如处理加载指示符,......)。

答案 2 :(得分:0)

不完全符合您的要求,但您可以生成这些回调&#34;即时&#34;:

function assignToScope(propName) {
    return function (data) { $scope[propName] = data; };
}

$http.get('/api/v1/movies/avengers').then(assignToScope('movieContent'));

或(如果您更喜欢这种语法):

function assignToScope(propName, promise) {
    promise.then(function (data) { $scope[propName] = data; });
}

assignToScope('movieContent', $http.get('/api/v1/movies/avengers'));

请注意错误处理很重要。如果承诺拒绝,您可能想要通知用户。