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

我试图将数据分配给$scope变量.在我的$promise.then()函数中,它正确显示但在函数外部显示为undefined.以下是我的控制器代码
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]

then()函数之外的结果:

undefined

我正在使用的’Tests’服务工厂如下:

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

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

});

即使我使用查询方法而不是get for my资源并将isArray设置为true,我仍然会遇到同样的问题.由于某种原因,数据没有绑定到then函数中的我的范围.

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

在此先感谢您的支持.

解决方法

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

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

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...