javascript - In angular service call not getting value at first time issue? -
here
attached sample program service call. in facing problem first time not getting value properly.
1st time invocation:
2nd or more invocation:
may know problem? , me fix. , why count executed first , datalength executed second?
$http.get
calling async default. have use promise make sync. use updated code refer plunker:
var app = angular.module('myapp', []); app.controller('myctrl', ['$scope', '$location', '$filter', 'sampleservice', '$http', function ($scope, $location, $filter, sampleservice, $http) { $scope.getcount = function () { sampleservice.getfile().then(function (data) { var dt = data.prtgetslotsbysessionresult; var count = $filter('filter')(dt, { "n": null }); alert(json.stringify(count.length)); }); } }]); app.factory('sampleservice', ['$http', '$filter', '$q', function ($http, $filter, $q) { return { object: '', makerequest: function (url) { // create deffered object var deferred = $q.defer(); $http.get(url).then(function (resp) { deferred.resolve(resp.data); }); return deferred.promise; }, getfile: function () { if (!this.object) { this.object = this.makerequest("file.json"); } // return myobject stored on service return this.object; } }; }]);
Comments
Post a Comment