【问题标题】:Angular Js - Why I am getting Undefiend in controller while I am getting data from service?Angularjs - 为什么我在从服务中获取数据时在控制器中得到未定义?
【发布时间】:2026-01-29 15:40:01
【问题描述】:

我提供了一项服务,我正在获取数据,但它没有向控制器返回任何内容。

我的服务。 js文件

app.factory('countryService', function ($http) {
    return {
        getCountries: function () {
            $http.get('http://abc/countries')
                    .success(function (data) {
                        console.log(data);
                    })
                    .error(function (data) {
                        console.log(data);
                    });
        }
    };
});

这是我的控制器

$scope.countries = function () {
            $scope.countries_data = countryService.getCountries();
            console.log($scope.countries_data);
        };

我的错误是什么?

【问题讨论】:

  • 尝试使用return 语句。有关详细信息,请参阅MDN JavaScript Reference -- return statement
  • @georgeawg only return 不起作用,因为.success & .error 函数已应用于$http.get,它将破坏承诺链,OP 必须删除 .success & @ 987654330@函数(这里也没什么特别的)

标签: angularjs http service factory


【解决方案1】:

您可能需要进行一些结构更改,如下所示

app.factory('countryService', function ($http) {
    return {
        getCountries: function () {
            return $http.get('http://abc/countries'); //just return promise
        }
    };
});

让服务返回promise,在控制器内部做其他处理,同样定义成功回调和失败回调

$scope.countries = function () {
    $scope.countries_data = countryService.getCountries().then(success, failure); // callbaks
};

function success(response){
   console.log(response); // logs the results
}

function failure(response){
   console.log(response); // logs the errors if any
}

希望这会有所帮助

【讨论】:

  • $http 方法确实返回 promise 对象本身,因此无需使用 $q 创建您自己的自定义 promise,那将是一个开销,我强烈建议您查看 @987654321 @,除非您有任何特殊情况,否则值得避免使用延迟模式..
  • 请注意,失败处理程序正在将被拒绝的承诺转换为成功的承诺。当函数缺少 return 语句时,它返回值 undefined。这会将被拒绝的承诺转换为以undefined 值解析的已履行承诺。存储在$scope.countries_data 中的承诺将是错误的。
【解决方案2】:

为您服务:

app.factory('countryService', function ($http) {
    return {
        getCountries: function () {
            return $http.get('http://abc/countries')  // add return this service
                    .success(function (data) {
                        console.log(data);
                    })
                    .error(function (data) {
                        console.log(data);
                    });
        }
    };
});

在控制器中:

$scope.countries = function () {
           countryService.getCountries().then(function(res){
 $scope.countries_data = res;
   console.log($scope.countries_data);
});

        };

【讨论】: