Angular controller can't get data from service

非 Y 不嫁゛ 提交于 2019-12-08 12:50:45

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/22154063/angular-controller-cant-get-data-from-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!