0

I think the title pretty sums up what I want to achieve. I looked in different SO threads regarding the issue, some uses $q while others do not. So I tried to pull something simple:

.factory('db',['$http',function($http){
    return{
        get:function(){
            $http.get('https://randomuser.me/api/');
        }
    }
}])

    .controller('PanelCtrl', [
    '$scope',
    'db',
    function($scope, db){
     db.get().then(function(response){
        $scope.player=response.data;
     });

Using Console.log I found that the data is fetched if I use the entire call inside the controller/factory. but here I'm getting undefined result in the $scope no matter what I do. The best outcome for me is to return the responsed data from factory to the $scope so all the $http call will be included inside my factory.

Johnny
  • 111
  • 3
  • 14

1 Answers1

2

Change

$http.get('https://randomuser.me/api/');

to

return $http.get('https://randomuser.me/api/');

Return is required here so that the caller can refer to the result.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • Still returning undefined for console.log($scope.player); – Johnny Jun 24 '17 at 10:08
  • @Johnny Please update your question, and post the exact error. – 31piy Jun 24 '17 at 10:09
  • @Johnny - What do you get in your console when your write `console.log(response)` as the first line in `.then()`? – 31piy Jun 24 '17 at 10:11
  • I'm getting an object with data,headers,config etc properties, obviously the problem is with the $scope assignment?.@31piy – Johnny Jun 24 '17 at 10:13
  • I think I figured it out.. I'm getting undefined when console.log($scope.player); line is outside "then" function. why is that happening? – Johnny Jun 24 '17 at 10:23
  • https://stackoverflow.com/questions/25274449/angularjs-promise-then-data-undefined – Johnny Jun 24 '17 at 10:26
  • 1
    @Johnny - Because the data doesn't exist at the time you're trying to log it. You've made an async call so you need to be sure to do things with the data only after such time as the data has been returned from the server, i.e. inside the `then` block. The code in that block only gets executed after the data has been returned (hence the word `then`). – Dan Jun 24 '17 at 17:03