Skip to content Skip to sidebar Skip to footer

Angularjs $http Data Not Returning Correctly

I'm trying to encapsulate data (via a JSON file) to be used across my controllers using a factory, though when I call the factory, it's executing my $scope before the data is retur

Solution 1:

The way it's usually done is that your data function returns a promise object. From conceptual standpoint if you deal with asynchronous operation like data retrieval, getData cannot (and should not) simply return the value, but rather a promise.

The basic idea is this:

angular.module('myApp')
.factory('StoreProducts', function ($http) {
    // ... return {
        // ...
        getData: function() {
            return$http.get('/example.json').then(function(response) {
                return response.data;
            });
        }
    };
});

which you later use in controller:

StoreProducts.getData().then(function(data) {
    $scope.data = data;
});

Of course you can add caching layer if you don't want to query server on each getData call. If cached value is available, then again return promise, but this time promise resolves immediately without making a request:

getData: function() {
    return storeData ? $q.when(storeData) : $http.get('/example.json').then(function(response) {
        storeData = response.data;
        return storeData;
    })
}

Demo: http://plnkr.co/edit/bM6AK5sEQ5ZEEad4BVUu?p=preview

Post a Comment for "Angularjs $http Data Not Returning Correctly"