Making a factory return the data of an Ajax request

2

I'm trying to make a factory return the JSON of an Ajax request that I'm doing, but I think because it's asynchronous, the container with the users always returns empty. So much that I tested with several console.log and the sequence of the calls was different.

Summarizing : what resource can I use for the factory to fill out the requisition data before returning so it does not come back empty?

    
asked by anonymous 12.08.2015 / 01:17

1 answer

1

In your case you can implement a Promises, so you can get the return of the request.

example implementation.

.factory('servico', function['$q', '$http', function ($q, $http) {

    return {
       method: function (objeto) {

           var deferred : $q.defer();
           $http.post('url', objeto)
           .success(function(data){
             deferred.resolve(data);
           }).error(function(data) {
             deferred.reject(data);
           });         
          deferred.promise;
       }
    }
}])

In your controller that injects your factory you will access the promises as follows

servico.method({objeto}).then(function(retorno){ $scope.suaVariavel = retorno }, function(retornoError){});

The Service Factory, is responsible for performing the request HTTP (ajax) and return if SUCCESS, its object, and if error, its error, thus the promise deferred, is responsible for launching a (resolve or reject) according to the http request. in your controller where you have injected the service, into the Then you get the return from the promises, implemented in the service and apply to your property.

Promises / Defered reference link

    
12.08.2015 / 15:43