Explanation of asynchronous data loading in AngularJS -
below example code in controller 2 console.log instructions. after accessing page in browser, list of users appears, displayed well. result of console.log :
the first one: after loadall() function call = 0
the second one: end of loadall() function = 8
angular.module('tessicommunicationapp') .controller('usermanagementcontroller', ['$scope', '$filter', '$log', 'principal', 'user', 'parselinks', 'language', 'ngtableparams', function ($scope, $filter, $log, principal, user, parselinks, language, ngtableparams) { $scope.users = []; $scope.authorities = ["role_user", "role_admin", "role_tc_admin", "role_tc_ges_adm", "role_tc_sui_tra", "role_tc_cons"]; language.getall().then(function (languages) { $scope.languages = languages; }); principal.identity().then(function (account) { $scope.currentaccount = account; }); $scope.page = 1; $scope.loadall = function () { user.query({ page : $scope.page - 1, size : 20 }, function (result, headers) { $scope.links = parselinks.parse(headers('link')); $scope.totalitems = headers('x-total-count'); $scope.users = result; console.log("end of loadall() function = " + $scope.users.length); }); }; $scope.loadpage = function (page) { $scope.page = page; $scope.loadall(); }; $scope.loadall(); console.log("after loadall() function call = " + $scope.users.length); } ]);
my question simple : why first 1 log print "0" whereas loadall() method called before.
because call asynchronous, in case means $scope.users.lenght
has not yet been populated when first log length (console.log("after loadall() function call = " + $scope.users.length);
). in "callback-function", when data has been fetched in $scope.loadall()
have recieved data , $scope.users
has been populated.
simply put, code executed directly after calling $scope.loadall()
, , not wait finish before running next line console.log("after loadall() function call = " + $scope.users.length);
Comments
Post a Comment