AngularJS $promise then() 数据未定义 [英] AngularJS $promise then() data undefined

查看:23
本文介绍了AngularJS $promise then() 数据未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get data assigned to a $scope variable. Inside my $promise.then() function it is displaying correctly but outside the function it shows as undefined. The following is my controller code:

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() 函数内部的结果:

The results inside the then() function:

[Object, Object, Object, Object]

then() 函数之外的结果:

The results outside the then() function:

undefined

我使用的测试"服务工厂如下:

The 'Tests' service factory I am using is the following:

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

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

});

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

Even when I use the query method instead of the get for my resource and set isArray to true I still end up with the same issue. For some reason the data is not binding to my scope inside the then function.

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

I am sorry if this is a repeat question but i looked everywhere and only found undefined issue relating to the $promise function which is no the issue in this case.

预先感谢您的支持.

推荐答案

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

The function passed to .then() will be called after the data has been fetched from the backend. The other console.log() (the one outside of .then()) will be called immediately after the request has been made, and not after it has been completed, thus the tasks is undefined.

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

Consider the timing (of course times are only an example):

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

这篇关于AngularJS $promise then() 数据未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆