David Dahan
David Dahan

Reputation: 11152

Getting data from service in controller does not work

I'm trying to do something simple but I don't understand why it does not work.

I just want to get the rewards data in the scope of my controller:

Services:

.factory('RewardModel', ['RewardsPromise', 'CardModel',
                         function(RewardsPromise, CardModel) {
  var RewardModel = {};

  RewardModel.rewards = undefined; // init

  RewardModel.getRewards = function() {
    RewardsPromise.getRewards().then(function(data){ // Call to a webservice (GET)
      RewardModel.rewards = data.objects;
    })
  };
  return RewardModel;
  }])


.factory('RewardsPromise', ['$http', '$q',
                             function ($http, $q) {
    return {
        getRewards: function() {
            return $http.get("http://some_url").then(function(response) {
                return response.data;
            });
        }
    };
}])

Controllers:

myAppControllers.controller('PromosCtrl', ['$scope', 'RewardModel',
                                            function($scope, RewardModel) {


    $scope.rwds = RewardModel.getRewards();

  }]);

In the end, $scope.rwds is empty. Note that I already tried to inspect data.objects and it contains the data.

Any idea? Thanks.

Upvotes: 0

Views: 69

Answers (2)

Brocco
Brocco

Reputation: 64843

The changes I'd make to your service (assuming you don't want to combine RewardsModel and RewardsPromise. In here I would make sure to still return the promise (for your controller's use) while still keeping the parsing of objects from your data

RewardModel.getRewards = function() {
    return RewardsPromise.getRewards()
        .then(function(data){
            return data.objects;
        });
};
return RewardModel;

And to your controller, you want to deal w/ the promise here and set the value on your scope once the promise has been resolved.

RewardModel.getRewards()
    .then(function(data){
        $scope.rwds = data;
    }, function(data){
        //handle any errors
    });

Upvotes: 1

a better oliver
a better oliver

Reputation: 26828

`$scope.rwds = RewardModel.getRewards();``

getRewards() does not return anything. It could return the promise. Then you could the the same in the controller as you do in the service.

Upvotes: 0

Related Questions