Researcher Researcher - 5 months ago 10
AngularJS Question

Factory in Service

I have a factory that i can't edit:

factory('UsersForAnimale', ['$q', '$http',function($q, $http) {
var getUsers = function() {
var deferred = $q.defer();

$http.get('ServerRest/users-for-animale.php')
.success(function(data) {
deferred.resolve(data); // Successo: risolvo la promise
})
.error(function(reason) {
deferred.reject(reason); // Errore: rigetto la promise
});

return deferred.promise; // Restituisco una promise
}

return {
getUsers: getUsers
};


}]);

I created a service because i want to try to manipulate the result:

.service('ContatoreUtentiAndPromise', ['UsersForAnimale',function(UsersForAnimale)
{

var Numero = 0;

this.getNumber = function()
{
UsersForAnimale.getUsers().then(function(data)
{
this.Numero = data.length;
console.log("Numero="+this.Numero);

this.Numero = this.Numero+10;

return this.Numero;

});



}

}]);


The console show me the correct value but controller show nothing.

.controller('ListaUtentiContaConSapInBoxCtrl', ['ContatoreUtentiAndPromise','$scope','$q', function (ContatoreUtentiAndPromise,$scope,$q)
{

$scope.numeroUtenti=ContatoreUtentiAndPromise.getNumber();


}]);


I wonder where I'm wrong

Answer

You should return the promise from your service method, because the factory method is asynchronous:

this.getNumber = function() {
    return UsersForAnimale.getUsers().then(function(data) {
        this.Numero = data.length;
        console.log("Numero="+this.Numero);

        this.Numero = this.Numero+10;

        return this.Numero;
    });
}

and then use it this way:

ContatoreUtentiAndPromise.getNumber()
.then(function(num) {
    $scope.numeroUtenti = num;
});
Comments