为什么没有从函数返回该值

Why is the value not returned from the function?

本文关键字:返回 函数 为什么      更新时间:2023-09-26

我在角度服务中有以下代码:

factory.getList = function(){
      $http.get('/getClasses')
                    .success(function (response) {
                        console.log(response);
                        return(response);
                    })
                    .error(function() {
                        console.log('error in getList');
                    });
            };

当我运行它时,我可以在控制台中看到响应,但在控制器中我有:

$scope.classesList = Svc.getList();

并且此类列表始终是未定义的。为什么?

它是一个

异步回调函数,你需要做一些事情

首先将调用 B 函数传递给服务

factory.getList = function(callb){
      $http.get('/getClasses')
                    .success(function (response) {
                        console.log(response);
                        callb(response);
                    })
                    .error(function() {
                        console.log('error in getList');
                    });
            };

然后在控制器中这样调用它

 Svc.getList(function(data){
 $scope.classesList=data;
 });