1

I have a factory with a HTTP GET request and I used promises as the documentations says I should, using $q service, but it is returning an empty promise:

App.factory('dataFactory', ['$rootScope','$http','$q', function($rootScope,$http,$q) {

  // Objeto del factory 
  var fac = {};

  // Funcion que obtiene un mensaje completo
  fac.obtenerListaMensajes = function(compania,userhid){

    var deferred = $q.defer(); 

    $http({ 
            method: 'GET', 
            url: urlListaMensajes, 
            params: {company:compania,userhid:userhid}
          }).
      then(function(response) {

        deferred.resolve(response.data.messages);

        console.log(JSON.stringify(deferred.promise));

        }, function(error) {
          deferred.reject(error);
    });

    return deferred.promise;
  };

  return fac;

}]);

The controller:

App.controller('MailFolderController', ['$scope','$rootScope','dataFactory', '$stateParams', function($scope, $rootScope, dataFactory, $stateParams) {

  // Variables de PRUEBA
  var user_prueba = 'MTQzMjU4NjUyNDcxMzczNzQwNjE3MTg1ODMxMDY5OTQ2';
  var company_prueba = 'development';

  $scope.mails = dataFactory.obtenerListaMensajes(company_prueba,user_prueba);
}]);

The final value in $scope.mails is:

{"$$state":{"status":0}}

I know for a fact that the HTTP request works properly thanks to the console.log inside it.

What am I doing wrong? I could use $rootScope to return the value, it works, but it would be a bad programming strategy.

1 Answer 1

5

Proper way to use service in controller would be:

dataFactory.obtenerListaMensajes(company_prueba, user_prueba).then(function(data) {
    $scope.mails = data;
});

Also you can improve service by getting rid of redundant dummy deferred object, you don't need it since $http already returns promise:

App.factory('dataFactory', ['$rootScope', '$http', '$q', function ($rootScope, $http, $q) {

    // Objeto del factory 
    var fac = {};

    // Funcion que obtiene un mensaje completo
    fac.obtenerListaMensajes = function (compania, userhid) {
        return $http({
            method: 'GET',
            url: urlListaMensajes,
            params: {
                company: compania,
                userhid: userhid
            }
        }).
        then(function (response) {
            return response.data.messages;
        });
    };

    return fac;

}]);
Sign up to request clarification or add additional context in comments.

1 Comment

So it was just ignorance from my part. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.