0

Recently I started learning AngularJS. My problem is as follows. I cannot access the data returned by $http.get() out side the method call.

Code :

(function(){
    var productApp = angular.module('productApp', []);

    productApp.controller('ProductController', ['$http', function($http){
        var store = this;
        store.products = [];

        $http.get('http://localhost:8080/VeggieFresh/veggie/product/1')
        .success(function(data){
            store.products = data;
            console.log(data);
        });
        console.log(store.products);
    }]);

})();

When I print data inside $http.get() method, it could be printed without any problem, but when i try to print it outside method; it displays empty array.

I guess because of this I cannot access this data on HTML as well. Any help in this regards is highly appreciated.

3 Answers 3

1

Since $http success is a asynchronous call you wont get data immediately outside the function you can call a function for "success" function , or use a callback function

As far as your code is concerned, you can save data on $scope variable

  $http.get('http://localhost:8080/VeggieFresh/veggie/product/1')
    .success(function(data){
        $scope.store.products = data;
        //console.log(data);
    });
Sign up to request clarification or add additional context in comments.

Comments

0

The success function runs async, so you will get the result inside success function.

Comments

0

Following code worked for me.

productApp.controller('ProductController', ['$http', function($http){
        var store = this;
        store.products = [];

        var promise = $http.get('http://localhost:8080/VeggieFresh/veggie/product/1');
        promise.success(function(data){
            store.products = data;
        });
}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.