Angular HTTP http data not returning correctly
I'm trying to encapsulate data (via a JSON file) to be consumed across my controllers using a factory, although when I call the factory it executes mine $scope
before returning the data, resulting in an empty array.
I want to get the data first, then execute my declarations $scope
that return my data, for example:
Factory:
angular.module('myApp')
.factory('StoreProducts', function ($http) {
var storeData = [];
var promise = $http.get('/example.json')
.success(function (data) {
storeData = data;
});
return {
promise: promise,
setData: function(data) {
storeData = data;
},
getData: function() {
return storeData;
}
};
});
Controller:
angular.module('myApp')
.controller('StoreCtrl', function ($scope, $log, StoreProducts) {
$scope.data = StoreProducts.getData();
$log.log($scope.data);
});
JSON file:
[
{
"productId": "1",
"name": "Example 1",
"price": "5.99"
},
{
"productId": "2",
"name": "Example 2",
"price": "2.99"
},
]
I think so because the scope is getData()
completely off, although I seem to think otherwise. What am I doing completely wrong?
source to share
As usual, your data function returns a promise object. Conceptually, if you're dealing with an asynchronous operation like fetching data, getData
it can't (and shouldn't) just return a 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 your controller:
StoreProducts.getData().then(function(data) {
$scope.data = data;
});
You can of course add a caching layer if you don't want to query the server on every call getData
. If a cached value is available, return the promise again, but this time the promise is immediately resolved without being prompted:
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
source to share