Skip to content Skip to sidebar Skip to footer

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(){ aler

Solution 1:

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

Solution 2:

$http is a asynchronous call, so what happens is that you have triggered a http call at line number 6 while it gets the response the line number 10 will be executed since all http calls in angular are asynchronous.

enter image description here

That is why you are getting undefined

If you want to do anything after the response just do the stuff within the http promise ie. within the .then function block like as shown below

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

Post a Comment for "Angularjs Http Get Response Is Undefined But The Data Is Present Inside Success Function"