2016-07-01 12 views
0

Ich habe eine Fabrik, die ich nicht ändern kann:Fabrik in Service

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 
}; 

}]);

habe ich einen Dienst, weil ich das Ergebnis wollen versuchen zu manipulieren:

nichts
.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; 

     }); 



    } 

}]); 

Die Konsole zeigt mir den richtigen Wert, sondern Controller zeigen.

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

    $scope.numeroUtenti=ContatoreUtentiAndPromise.getNumber(); 


}]); 

Ich frage mich, wo ich falsch

Antwort

1

Sie sollten das Versprechen von Ihrer Service-Methode zurückkehren, weil die Factory-Methode asynchron:

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; 
    }); 
} 

und dann auf diese Weise verwenden:

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

Großartig! Vielen Dank! – Researcher

Verwandte Themen