Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs http get response is undefined But the data is present inside success function

Am new to angular. I have tried to get the json response from http get method.

My code is,

app.factory('getdata', function ($http, $q){
  this.getlist = function(){       
    alert('1');
    return $http.get('http://www.w3schools.com/angular/customers.php',{'Access-Control-Allow-Origin': 'localhost:*'})
    .then(function(response) {
      console.log('response'); console.log(response.data); //I get the correct items, all seems ok here
        alert('2');
        return response.data;
      });            
  }
  return this;
});
/* Stream page controller */
app.controller('streamCtrl', function($scope,getdata, $ionicSlideBoxDelegate, $timeout, $ionicScrollDelegate, $location, $sce){
  $scope.trustSrc = function(src) {
    return $sce.trustAsResourceUrl(src);
  }
  getdata.getlist()
  .then(function(arrItems){
   $scope.sliders = arrItems;         
 });
alert($scope.sliders);

am getting the alert like 1, 'undefined' and 2 but the $scope.sliders has the data. because It was working once I resize the screen and also I can get correct alert inside the

getdata.getlist().then(function(arrItems) {
  $scope.sliders = arrItems;         
  alert($scope.sliders);
});
like image 728
Anandhakumar R Avatar asked Dec 24 '22 13:12

Anandhakumar R


1 Answers

The reason for getting alert is undefined is because you haven't define $scope.sliders in controller and http request is async so alert($scope.sliders); function call before getting data from response and setting that data to $scope.sliders.

You get alert($scope.sliders); value only after getting success response.

Other possibility is you can set $scope.sliders = {} and then use alert($scope.sliders); which show {} in alert when then function is called alert shows actual response.

Original plunker based on issue

Check comments and updated code in new plunker

like image 111
Sarjan Desai Avatar answered Dec 28 '22 11:12

Sarjan Desai