角控制器不能从业务数据 [英] Angular controller can't get data from service

查看:277
本文介绍了角控制器不能从业务数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我在学习AngularJS,我已经写了样品code为一个模块创建服务,并从服务的数据传递到模块的控制器之一,一切工作正常。

不过,昨天当我尝试下面的服务的数据传递到控制器,它只是显示的数据是不确定的,我不知道为什么。

  VAR notif = angular.module('testnotif',[]);notif.service('sharedUsers',['$ HTTP',函数($ HTTP){
  VAR URL = current_dir +'/ testNotif / getAllUsersjson';
  VAR ALLUSERS = [];
  VAR GETALL =功能(){
    $ http.get(URL)
    .success(功能(数据,状态){
      data.forEach(功能(用户){
        ALLUSERS [用户['ys_user_id'] =用户;
      });      的console.log('服务');
      的console.log(ALLUSERS); //此处控制台显示ALLUSERS数据从服务器上获取正确的。      返回ALLUSERS;
      });
    };   返回{
       GETALL:GETALL
   };
}]);notif.controller('notifCtrl',['$范围,$ HTTP,$超时','sharedUsers',
                              功能($范围,$ HTTP,$超时,sharedUsers){    $ scope.allUsers = sharedUsers.getAll(); //shareUsers.getAll()返回任何内容
    的console.log('在notifCtrl');
    的console.log($ scope.allUsers); //控制台仅仅打印未定义。什么不顺心?
}]);

该服务有一个GETALL属性,它是一个函数获取ALLUSERS数据。
在控制台它显示ALLUSERS已经填充了来自服务器的数据,
但在控制器,当我把这个GETALL()函数,它没有返回值。
什么是我的code中的问题?
非常感谢你!

编辑:现在我得到的数据正确,这要归功于@doodeec您指出的回归的错误,并承诺使用API​​建议。并感谢@ IntegrityFirst指出了不断注入一种更好的方式。以下code是工作版本,以防万一有人想知道。

  //定义常量:
notif.value('current_dir','目录到当前路径');
//模块,定义服务
notif.service('sharedUsers',['$ HTTP,$ Q','current_dir',函数($ HTTP,$ Q,current_dir){
VAR URL = current_dir +'/ testNotif / getAllUsersjson';
VAR ALLUSERS = [];VAR GETALL =功能(){
    变种推迟= $ q.defer();
    $ http.get(URL)
    .success(功能(数据,状态){
        data.forEach(功能(用户){
            ALLUSERS [用户['ys_user_id'] =用户;
        });
        的console.log('服务');
        的console.log(ALLUSERS);
        deferred.resolve(ALLUSERS);
    });
    返回deferred.promise;
};
返回{
     GETALL:GETALL
};
}]);
//在控制器
notif.controller('notifCtrl',['$范围,$ HTTP,$超时','sharedUsers','$ Q',
                              功能($范围,$ HTTP,$超时,sharedUsers,$ Q){
sharedUsers.getAll(),然后(功能(数据){$ scope.allUsers =数据;});
}]);


解决方案

GETALL 是函数,它不返回任何东西,这就是为什么 $范围.allUsers 未定义

您可能想这样做。

控制器 - $同时承诺,从返回C $按c等待 GETALL 得到解决,并指定数据从承诺范围变量返回

  sharedUsers.getAll(),然后(功能(数据){$ scope.allUsers =数据;});

服务 - $ http.get 的回报承诺,所以你可以在方法调用返回它,这样你就能做出反应的决心/拒绝控制器

  VAR GETALL =功能(){
    返回$ http.get(URL)
        .success(功能(数据,状态){
            data.forEach(功能(用户){
                ALLUSERS [用户['ys_user_id'] =用户;
            });
            返回ALLUSERS;
        });
};

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

这篇关于角控制器不能从业务数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆