javascript - AngularJS $promise then() 数据未定义

标签 javascript angularjs angularjs-scope angular-resource angular-promise

我正在尝试将数据分配给 $scope 变量。在我的 $promise.then() 函数内它显示正确但在函数外它显示为未定义。以下是我的 Controller 代码:

angular.module('testSiteApp').controller('TestController', function ($scope, Tests) { 

$scope.test = Tests.get({id: 1});

$scope.test.$promise.then(function(data) {
    $scope.tasks = data.tasks;
    console.log($scope.tasks);
});

console.log($scope.tasks); 

});

then() 函数内的结果:

[Object, Object, Object, Object]

then()函数外的结果:

undefined

我正在使用的“测试”服务工厂如下:

angular.module('testSiteApp').factory('Tests', function($resource) {

return $resource('/api/test/:id', {id: '@id'}, { 'update': { method: 'PUT' } } );

});

即使我对我的资源使用查询方法而不是 get 方法并将 isArray 设置为 true,我仍然会遇到同样的问题。由于某种原因,数据未绑定(bind)到 then 函数内的范围。

如果这是一个重复的问题,我很抱歉,但我到处查看,只发现与 $promise 函数相关的未定义问题,这在这种情况下不是问题。

在此先感谢您的支持。

最佳答案

传递给 .then() 的函数将在从后端获取数据后调用。另一个 console.log()(.then() 之外的那个)将在发出请求后立即调用,并且不是在完成之后,因此 tasks 是未定义的。

考虑时机(当然时间只是一个例子):

// time = 0.000 sec. You make a request to the backend
$scope.test = Tests.get({id: 1});

$scope.test.$promise.then(function(data) {
    // time = 1.000 sec. Request is completed. 
    // data is available, so you assign it to $scope.tasks
    $scope.tasks = data.tasks;
    console.log($scope.tasks);
});

// time = 0.000 sec (!!!) This has been called NOT AFTER
// the callback, but rather immediately after the Tests.get()
// So the data is not available here yet.
console.log($scope.tasks); 

关于javascript - AngularJS $promise then() 数据未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274449/

相关文章:

javascript - 作用域未在处于不同状态的函数内更新

javascript - 更改范围变量时无法获取范围变量长度

javascript - 无法通过 $scope 获取 ng-model 的值

javascript - 函数前的感叹号有什么作用?

javascript - 如何仅在angularjs中将小数限制为2位

javascript - 如何在模板中组织 Canvas 脚本

javascript - 如何在小部件中添加外部 javascript 库和样式表?

angularjs - 如何将 JWT token 存储在仅 HTTP 的 cookie 中?

javascript - 折叠/展开 Swagger 响应模型类

javascript - 如何为显示标签表中的行赋予唯一的行ID?