我开发一个小AngularJS应用程序,我目前正在创建一个服务中挣扎。
I'm developing a small AngularJS app and I'm currently struggling with creating a service.
我有作为用于提供触点的后端(姓名,地址...)的服务。到现在为止,他们硬codeD作为服务( instance.contacts = [...]
)的数组,但现在我想读他们从JSON文件:
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;
}]);
我看到,该文件已经被成功读取我的浏览器控制台,但我看不到屏幕上的任何变化。
所以,我想下面的,而是和它的工作:
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;
}]);
我不知道为什么第二code片段的作品,而不是第一个。可能有人请帮助我理解?
I don't know why the second code snippet works, and not the first. Could someone please help me understand ?
推荐答案
$ HTTP
是异步的,所以你不能返回数组,因为当你回来时,它可能不会有它的任何数据。实际上,你必须退回承诺:
$http
is asynchronous, so you can't return an array because when you return it, it probably doesn't have any data in it yet. You actually have to return the promise:
var instance = $http('contacts.json');
return instance;
然后在你的控制器(或其他服务):
And then in your controller (or in another service):
contactService.then(function(response) {
$scope.contacts = response.data;
});
请记住,无论你在哪里访问你的服务,你必须用它作为一个承诺使用交互然后
。
相关推荐
最新文章