Thursday, March 29, 2018

javascript - JSON to Initialize Data in Service

I'm developing a small AngularJS app and I'm currently struggling with creating a service.


I have a service that serves as a backend for providing contacts (name, address...).
Until now they were hard-coded as an array in the service (instance.contacts=[...]), but now I'm trying to read them from a json file :


myModule.factory('contactService', ['$http',function ($http) {
var instance = {};
$http.get('contacts.json').success(function (data) {
instance.contacts = data;
});
return instance;
}]);

I see in my browser console that the file has been read successfully, but I don't see any change on-screen.


So I tried the following instead, and it worked :


myModule.factory('contactService', ['$http',function ($http) {
var instance = {
contacts:[]
};
$http.get('contacts.json').success(function (data) {
angular.forEach(data, function(item) {
instance.contacts.push(item);
});
});
return instance;
}]);

I don't know why the second code snippet works, and not the first. Could someone please help me understand ?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...