質問

Background: I'm learning AngularJS, I've written sample code to create a service for a module, and pass the data from service into one of the module's controller, all works fine.

But yesterday when I tried to pass the following service's data into a controller, it just show the data is undefined, and I don't know why.

var notif = angular.module('testnotif',[]);

notif.service('sharedUsers', ['$http', function($http){
  var url = current_dir+'/testNotif/getAllUsersjson';
  var allUsers = [];  
  var getAll = function (){
    $http.get(url)
    .success(function(data, status) {        
      data.forEach(function(user){
        allUsers[user['ys_user_id']]=user;
      });

      console.log('in service'); 
      console.log(allUsers);//here console shows allUsers data correctly fetched from server. 

      return allUsers;
      });
    };

   return {
       getAll: getAll
   };
}]);

notif.controller('notifCtrl',['$scope','$http', '$timeout','sharedUsers', 
                              function($scope, $http, $timeout,sharedUsers ){

    $scope.allUsers=sharedUsers.getAll(); //shareUsers.getAll() returns nothing
    console.log('in notifCtrl');
    console.log($scope.allUsers); //console just prints 'undefined'. what goes wrong?
}]);

the service has a getAll property which is a function get allUsers data. in the console it shows allUsers are populated with data from server already, but in the controller, when I call this getAll() function, it returns nothing. what is the problem with my code? thank you very much!

Edit: now I got the data correct, thanks to @doodeec for pointing out the 'return' error, and suggesting using promise api. and thanks to@IntegrityFirst points out a better way for injecting constant. the following code is the working version, just in case anyone wants to know.

//define constant:
notif.value('current_dir', 'dir to current path');
//in module, define service
notif.service('sharedUsers', ['$http','$q','current_dir', function($http, $q, current_dir){
var url = current_dir+'/testNotif/getAllUsersjson';
var allUsers = [];  

var getAll = function (){
    var deferred = $q.defer();
    $http.get(url)
    .success(function(data, status) {        
        data.forEach(function(user){
            allUsers[user['ys_user_id']]=user;
        });
        console.log('in service'); 
        console.log(allUsers);
        deferred.resolve(allUsers);         
    });
    return deferred.promise;
};
return {
     getAll: getAll
};
}]);
//in controller
notif.controller('notifCtrl',['$scope','$http', '$timeout','sharedUsers','$q', 
                              function($scope, $http, $timeout,sharedUsers,$q ){
sharedUsers.getAll().then(function(data){$scope.allUsers=data;});
}]);
役に立ちましたか?

解決

getAll is function which doesn't return anything, that's why $scope.allUsers is undefined

You probably want to do this

controller - code will wait while promise returned from getAll is resolved, and assign the data returned from that promise to scope variable

sharedUsers.getAll().then(function(data) { $scope.allUsers = data; });

service - $http.get returns promise, so you can return it in method call, so you will be able to react on resolve/reject in the controller

var getAll = function (){
    return $http.get(url)
        .success(function(data, status) {        
            data.forEach(function(user){
                allUsers[user['ys_user_id']]=user;
            });    
            return allUsers;
        });
};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top