javascript - Asynchronously function returns undefined with $q deferred -


i calling data api through factory looks this:

app.factory('service', ['$http', function ($http) {  var urlbase = 'http://localhost:50476/api'; var service = {};  service.getcomp = function () {     return $http.get(urlbase + '/complaints')  };  return service; }]); 

then use controller use directive:

getcomp(); $scope.comp = [];  function getcomp() {     var deferred = $q.defer();      service.getcomp()     .success(function (comp) {         console.log('comp', comp); //returns array data         $scope.comp = comp.data;         deferred.resolve(comp);     })     .error(function (error) {         $scope.error = 'error' + error.message;     });      return deferred.promise; }  $scope.index = 0; $scope.complaints = $scope.comp[0]; console.log($scope.complaints); //undefined console.log($scope.comp); //array of 0 

when try access items outside of function undefined. tried resolutions using $q still not displaying data. when added deferred part ng-repeat stops working well.

try this:

getcomp(); $scope.comp = [];  function getcomp() {     return service.getcomp()     .success(function (comp) {         $scope.comp = comp.data;         $scope.complaints = $scope.comp[0];     })     .error(function (error) {         $scope.error = 'error' + error.message;     }); } 

the values undefined when logs because lines run before request comes server. that's why setting $scope.complaints has go success callback.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -