0

I am writing a program to connect to a rest api... But factory function doesnt work ... While everything seems to be correct

factory:

app.factory('publisherService', ['$http', function($http){
  var services = {};
  var userInfo = {};
  services.getUser = function()
    {
        $http({method: 'GET', url: '/phoenix/publisher/user'}).success(function(data){
            userInfo = data;
        });

        return userInfo;
    };

  return services;
}]);

controller:

app.controller('publisher', ['$scope','publisherService', '$http',function($scope, publisherService,$http)
{
  $scope.publisher = {};
  $scope.publisher = publisherService.getUser();
}]);

When program runs $scope.publisher returns {}

But the following code runs well

app.controller('publisher', ['$scope','publisherService', '$http',function($scope, publisherService,$http)
{
  $scope.publisher = {};
  $http( {method: 'GET', url: '/phoenix/publisher/user'} ).success(function(data){
            $scope.publisher = data;
});
}]);
yousef
  • 92
  • 1
  • 10
  • Your `getUser` method should return the promise created via `$http`, eg `return $http(...).then(res => res.data);` – Phil Aug 23 '16 at 01:23
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil Aug 23 '16 at 01:23
  • 1
    Also, you're using a [deprecated API](https://docs.angularjs.org/api/ng/service/$http#deprecation-notice) – Phil Aug 23 '16 at 01:24

2 Answers2

0

The problem was resolved using $q... $q is well explained in this article.

yousef
  • 92
  • 1
  • 10
0

The service should return a promise:

app.factory('publisherService', ['$http', function($http){
  var services = {};
  var userInfo = {};
  services.getUser = function()
    {
        var promise = $http({method: 'GET', url: '/phoenix/publisher/user'});

        return promise;
    };

  return services;
}]);

Then the controller should use the promise:

app.controller('publisher', function($scope, publisherService,$http)
{
  var promise = publisherService.getUser();
  promise.then( function onSuccess(result) {
      $scope.publisher = result.data;
  });
});

The reason that the service was returning an empty object was that the function given as an argument to the .success method is held by the $q service until results from the XHR return. The $q stores the function and only invokes it when results are available. The empty object was returned to the service function before the XHR completed.

Have the service function return the XHR promise, and then have the onSuccess function put the results on $scope.

georgeawg
  • 48,608
  • 13
  • 72
  • 95