AngularJS $ then promises () undefined data

I am trying to get the data assigned to the $ scope variable. Inside my function $ prom.then (), it displays correctly, but outside the function it displays as undefined. Below is the code of my 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); }); 

Results inside the then () function:

 [Object, Object, Object, Object] 

Results outside the then () function:

 undefined 

Service "Tests" factory I use the following:

 angular.module('testSiteApp').factory('Tests', function($resource) { return $resource('/api/test/:id', {id: '@id'}, { 'update': { method: 'PUT' } } ); }); 

Even when I use the request method instead of get for my resource and set isArray to true, I still get the same problem. For some reason, the data is not required for my area inside the then function.

I apologize if this is a recurring question, but I searched everywhere and found an undefined problem related to the function $ prom, which in this case is not a problem.

Thanks in advance for your support.

+6
source share
3 answers

The function passed to .then() is called after the data has been retrieved from the backend. Another console.log() (one outside of .then() ) will be called immediately after the request and after completion , so tasks undefined.

Consider time (of course, time is just 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); 
+12
source

This is a promise, so it returns $ scope.task after . Until this happens, $ scope.task will be undefined, as your second console.log shows. At a later time, the promise will be resolved (completed), and $ scope.task matters, as your first console.log shows.

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

try it

+1
source

Source: https://habr.com/ru/post/973727/


All Articles