Making a Factory return data from an Ajax request

Asked

Viewed 117 times

2

I’m trying to make a Factory that returns the JSON of an Ajax request that I’m making, only, I think because it’s asynchronous, the container with the users always comes back empty. So much so that I tested with several console.log and the sequence of calls was different.

In short: which feature can I use to have Factory fill in the request data before returning so that it doesn’t come back empty?

1 answer

1

In your case you can implement a Promises, with this you can catch the return of the request.

example of 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 as follows to

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

o Factory Service, is responsible for performing the HTTP request (ajax) and return if SUCCESS, your object, and if error, your error, with that the File deferred, is responsible for launching one (resolve or Reject) according to the http request. in your controller where you injected the service, within the Then you take the return of the files, implemented in the service and apply p/ your property.

Reference of Names/Defered https://docs.angularjs.org/api/ng/service/$q

Browser other questions tagged

You are not signed in. Login or sign up in order to post.