Adam Pietrasiak
Adam Pietrasiak

Reputation: 13184

AngularJS promises without callback?

Usually when I'm getting some data async way I would do it like

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

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

In fact the scenario is very common - I send some request and when it's ready, I assing EVERYTHING it returns to some variable/prop. But everytime it require to make callback even if the callback is always the same.

Is there any way to do it like

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

or kind of

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

It's not big deal but when used a lot makes difference in my opinion.

Upvotes: 4

Views: 579

Answers (3)

Michael Kang
Michael Kang

Reputation: 52847

You can design your service so that it returns an empty reference and populates itself when the service call returns successfully. Use angular.copy to preserve the reference:

Service

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

Controller

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

});

Upvotes: 1

thriqon
thriqon

Reputation: 2488

Not exactly what you asked for, but you can generate these callbacks "on-the-fly":

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

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

or (if you like this syntax more):

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

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

Please note that error handling is important. If the promise rejects, you probably want to notify the user.

Upvotes: 0

Himmet Avsar
Himmet Avsar

Reputation: 1531

You could wrap the async call in a function:

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

*But I would not recommend you doing this. Often, you want to perform specific tasks in the callback function (like handling loading indicators, ...).

Upvotes: 0

Related Questions