AngularJS 从服务加载数据 [英] AngularJS Load Data from Service
问题描述
我在从填充到我的视图中的服务获取数据时遇到问题.我有一个这样定义的服务
I am having a problem getting data from a service populated into my view. I have a service defined as such
app.factory('nukeService', function($rootScope, $http) {
var nukeService = {};
nukeService.nuke = {};
//Gets the list of nuclear weapons
nukeService.getNukes = function() {
$http.get('nukes/nukes.json')
.success(function(data) {
nukeService.nukes = data;
});
return nukeService.nukes;
};
return nukeService;
});
和我的控制器
function NavigationCtrl($scope, $http, nukeService){
/*$http.get('nukes/nukes.json').success(function(data) {
$scope.nukes = data;
});*/
$scope.nukes = nukeService.getNukes();
}
如果我使用控制器中的 $http.get 数据填充得很好,但是,如果我尝试从服务调用数据,我什么也得不到.我知道查询是异步的,但我很难理解如何在返回数据后填充 $scope 变量.我可以使用 $rootscope 广播一个事件并在控制器中侦听它,但这似乎不是实现此目的的正确方法.我真的很感激关于如何以正确的方式做到这一点的任何建议.
If I use the $http.get from the controller the data populates fine, however, if I try to call the data from the service, I get nothing. I understand that the query is asynchronous but I am having a hard time understanding how to populate the $scope variable once the data is returned. I could use $rootscope to broadcast an event and listen for it in the controller but this does not seem like the correct way to accomplish this. I would really appreciate any advice on how to do this the correct way.
推荐答案
我认为这应该可以解决您的问题
I think this should solve your problem
app.factory('nukeService', function($rootScope, $http) {
var nukeService = {};
nukeService.data = {};
//Gets the list of nuclear weapons
nukeService.getNukes = function() {
$http.get('nukes/nukes.json')
.success(function(data) {
nukeService.data.nukes = data;
});
return nukeService.data;
};
return nukeService;
});
function NavigationCtrl($scope, $http, nukeService){
$scope.data = nukeService.getNukes();
//then refer to nukes list as `data.nukes`
}
这是对象引用的问题.
当您调用 nukeService.getNukes()
时,您将获得对对象 a
的引用,然后您的变量 $scope.nukes
引用该对象内存位置.
when you calls nukeService.getNukes()
you are getting a reference to a object a
then your variable $scope.nukes
refers that memory location.
在远程服务器调用后,当您设置 nukeService.nukes = data;
时,您不会更改对象 a
而是更改 nukeService.nukes
从引用对象 a
到对象 b
.但是你的 $scope.nukes
不知道这个重新分配,它仍然指向对象 a
.
After the remote server call when you set nukeService.nukes = data;
you are not changing the object a
instead you are changing nukeService.nukes
from referencing object a
to object b
. But your $scope.nukes
does not know about this reassignment and it still points to object a
.
在这种情况下,我的解决方案是传递一个带有属性 data
的对象 a
,然后只更改 data 属性而不是更改对 a
的引用>
My solution in this case is to pass a object a
with property data
and then only change the data property instead of changing reference to a
这篇关于AngularJS 从服务加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!