AngularJS promises without callback?

Usually, when I get some async way of data, I would do it like

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

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

In fact, the script is very common - I send some kind of request, and when it is ready, I am sure that it returns to some variable / prop. But every time a callback is required, even if the callback is always the same.

Is there any way to do this like

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

or kind

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

It doesnโ€™t matter, but when used, a lot makes a difference in my opinion.

+4
source share
3 answers

, , . 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

:

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

* . (, ,...).

0

, , " ":

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'));

, . , , , .

0

Source: https://habr.com/ru/post/1569703/


All Articles