Question

I am developing an angularjs app as a part of my angularjs learning. I have controllers and from there I am calling service layers.

leagueManager.service("teamsService", function($http){
    var teams = {};
        $http.get('data/teams.json').then(function(data) {
        teams = data;
    });
    this.getTeams = function(){
        return teams;
    };

});

I noticed that because of the asynchronous nature of $http.get.then stuff, the data is not retrieved immediately and hence I would not get the "teams" when I would call getTeams() from the controller (teamsController), I would get nothing.

Any idea how do I resolve this?

Second Attempt: After reading about deferred and promises on angular as suggested by the post below, I tried following but it still has no effect. My variable teams is not being populates as I want and they are populated afterwards and that is not helping in my UI:

My controller teamsController.js

leagueManager.controller('teamsController', function($scope, $location, teamsService, $routeParams){
//init function to initialize data when controller is called everytime.
var init = function(){
        $scope.teams = [];
        var promise = teamsService.getTeams();
        promise.then(
        function(data){
            console.log("teams after promise:="+data);
            $scope.teams = data;
        }
        ,function(reason)
        {
                alert('Failed: ' + reason);
        }
        );
        console.log("teams in the scope:="+$scope.teams);
};

init();
});

And here is my ServiceLayer teamsService.js

leagueManager.service("teamsService", function($http, $q){
this.getTeams = function(){
  var deferred = $q.defer();
     var url = 'data/teams.json';
     $http.get(url).success(function(data, status) {
         // Some extra manipulation on data if you want...
         deferred.resolve(data);
     }).error(function(data, status) {
         deferred.reject(data);
     });
     return deferred.promise;
}
});

Can you or someone help me what I am doing wrong? This is what is printed in the browser console upon execution:

teams in the scope:= teamsController.js:27

teams after promise:=[object Object],[object Object],[object Object],[object Object],[object Object]

This simply shows that I do get the json object but not at the time I want. For some reason this deffered/promise thing had no impact.

PLEASE HELP THIS NEW ANGULAR ENTHUSIAST

Was it helpful?

Solution

Yeah you will need to use a promise interface. So instead of returning a teams object, directly you'll have to return a promise:

Promise Resources:

In the service:

leagueManager.service("teamsService", function($http){
    var deferred = $q.defer();
    $http.get('data/teams.json').then(function(data) {
        deferred.resolve(data);
    });
    this.getTeams = function(){
        return deferred.promise;
    };
});

Then in the controller:

$scope.team = {};

var promise = teamsService.getTeams();
promise.then(function(data) {
    $scope.teams = data;
});

OTHER TIPS

This should work fine:

myApp.factory('mainFactory',['$http',function($http){

var mainFactory = {};

mainFactory.getRandomUser = function(){
    var promise;
    if(!promise){
        promise = $http.get('http://api.randomuser.me/').success(function(d){
            return d;   
        });
        return promise;
    }
};

mainFactory.getRandomImage = function(){
    var promise;
    if(!promise){
        promise = $http.get('http://lorempixel.com/400/200/').success(function(d){
            return d;   
        });
        return promise;
    }
};

return mainFactory;

}]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top