我有一个工厂,我从API中提取数据并尝试将结果分配给变量。每次我跑,我得到我的变量是未定义的。我可以通过异步调用将结果传递给变量的任何方式吗? 比如我的情况。我的工厂看起来像这样。
angular.module('MyApp.services', [])
.factory('ReportService', ['$http', '$window', '$upload', 'AuthService', function ($http, $window, $upload, AuthService) {
return {
findAll: function (criteria) {
criteria = criteria || [];
return $http.get(BASE_URL + '/ajax.php?action=reports.all&' + criteria.join('&'));
}
}
}])
然后在我的控制器中
.controller('MyViewController', [
'$scope', 'ReportService', 'toaster', '$modal', '$rootScope',
function ($scope, ReportService, toaster, $modal, $rootScope) {
ReportService
.findAll()
.then(
function success(response, status, headers, config) {
$scope.reports = response.data.reports;
},
function error(response, status, headers, config) {
console.log('error');
});
//console.log($scope.reports) returns undefined here.
}
]);
如何在控制器的全局级别填充变量?
答案 0 :(得分:0)
调用console.log($scope.reports)
时未定义变量的原因是因为您的代码是异步的。因此,您在http请求返回之前执行console.log($scope.reports)
并导致为$scope.reports
变量分配返回的数据。这只是异步代码的本质。
以下是按时间顺序发生的事情:
ReportService.findAll()
console.log($scope.reports)
ReportService.findAll()
的承诺解决并调用您的成功回调,然后设置$scope.reports = response.data.reports;
正如您所看到的,当您在步骤2中调用console.log
时,您的变量未定义是有意义的。因此,您的变量是在控制器中定义/填充的,而不是在您拨打console.log($scope.reports)
的时间点。
答案 1 :(得分:0)
当您的服务返回响应时,console.log($scope.reports)
正在执行。因此,你得到未定义
请将您的控制台声明放在.then(function success(){
它不会是未定义的,它会打印报告
.controller('MyViewController', [
'$scope', 'ReportService', 'toaster', '$modal', '$rootScope',
function ($scope, ReportService, toaster, $modal, $rootScope) {
ReportService
.findAll()
.then(
function success(response, status, headers, config) {
$scope.reports = response.data.reports;
console.log($scope.reports) // put it here // #2 won't be undefined.
},
function error(response, status, headers, config) {
console.log('error');
});
//console.log($scope.reports) returns undefined here. //#2 remove from here
}
]);