AngularJs http gets undefined response But data is present inside success function

New in angular. I tried to get json response from http get method.

My code

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);

I get a warning like 1, 'undefined' and 2, but $ scope.sliders data has data. because it worked as soon as I resize the screen, and also can get the correct warning inside

getdata.getlist().then(function(arrItems) {
  $scope.sliders = arrItems;         
  alert($scope.sliders);
});
+4
source share
2 answers

The reason for receiving the warning is undefined because you have not defined it$scope.sliders in the controller, and the request httpis async, so the function is called alert($scope.sliders);before you get datafrom the response and set this data to $scope.sliders.

alert($scope.sliders); .

- $scope.sliders = {}, alert($scope.sliders);, {} , then alert .

plunker

plunker

+6

$http - , , HTTP- 6, 10 , http angular .

enter image description here

undefined

- , http-, . .then,

getdata.getlist()
  .then(function(response){ // http promise block
     $scope.sliders = response.data;
     console.log($scope.sliders);
});
+4

Source: https://habr.com/ru/post/1613590/


All Articles