my code
/* code written factory */ /** * service/factory * * description */ angular .module('translationapp') .factory('logservice', logservice); logservice.$inject = ['$rootscope','$http', '$q', 'api_url']; function logservice ($rootscope,$http, $q,appurl) { var req = { method: 'get', url: appurl+'getlogs', } var defer = $q.defer(); var logdata = { getlogs : getlogs, alllogs : [] } return logdata; function getlogs () { $http.get('http://localhost/welcome_translation/getlogs') .then(getlogscomplete) .catch(getlogsfailed); return defer.promise; } function getlogscomplete (response) { logdata.alllogs = response.data; console.log('responsedata ='+json.stringify(logdata.alllogs)); // getting data here defer.resolve(response); } function getlogsfailed () { defer.reject('some error'); } } /* code controller */ /* controller logs */ angular .module('translationapp') .controller('logscontroller', ['$rootscope','$scope', '$http', 'api_url','$filter' , 'ngtableparams', 'logservice' , function($rootscope, $scope,$http, appurl,$filter, ngtableparams, logservice){ $scope.currentindex = 1; $scope.logs = logservice.alllogs; logs(); function logs() { /** * step 1 * ask getlogs function * logs data , wait promise */ return getlogs().then(function(response) { /** * step 4 * perform action on resolve of final promise */ //console.log(json.stringify(response.data)); $scope.logs = response.data; console.log(json.stringify($scope.logs)); // here getting data //return $scope.logs; }); } console.log('all log ='+ json.stringify($scope.logs)); // getting no data here function getlogs() { /** * step 2 * ask data service data , wait * promise */ return logservice.getlogs() .then(function(data) { /** * step 3 * set data , resolve promise */ return data; }); } /* list of roles */ $http.get(appurl+'getroles') .success(function (response) { $scope.roles = response; }); $scope.ontimeset = function (newdate, olddate) { $scope.formatteddate = $filter('date')(newdate, 'dd-mm-yyyy') } $scope.tableparams = new ngtableparams( { page: 1, count: 5, }, { total: $scope.logs.length, counts: [], getdata: function($defer, params) { $scope.data = $scope.logs.slice((params.page() - 1) * params.count(), params.page() * params.count()); $defer.resolve($scope.data); } }); }]);
i extracted relevant part of code:
getlogs().then(function(response) { $scope.logs = response.data; console.log(json.stringify($scope.logs)); // here getting data }); console.log('all log ='+ json.stringify($scope.logs)); // getting no data here
the problem success handler passed then
called asynchronously when logs retrieved. however, console.log
see no output happens right after request logs has been issued long before retrieved. that's whole point promises. pass handler execute once results there. can other stuff regardless how long takes until promise fulfilled.
if not clear recommend start js promise tutorial teaches main concepts need understand. post might helpful:
Comments
Post a Comment