AngularJS $ promise then()数据未定义 [英] AngularJS $promise then() data undefined
问题描述
我正在尝试将数据分配给$ scope变量。在我的$ promise.then()函数中,它正确显示但在函数外部显示为undefined。以下是我的控制器代码:
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
我使用的'Tests'服务工厂如下:
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 for my资源并将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.
提前感谢您的支持。
推荐答案
传递给<的函数从后端获取数据后,将调用code> .then()。另一个 console.log()
( .then()
之外的那个)将立即被称为请求完成后,完成后 ,因此任务
未定义。
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屋!