我正在尝试使用AngularJS中的服务从外部文件加载JSON数据。
myApp.service('ContactsListService', function($http) {
var contactsList = $http.get('js/contacts.json').success(function(data){
return data;
});
console.log(contactsList); // prints some $http object
return {
'contactsList': contactsList;
};
}
myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
$scope.contacts = ContactsListService.contactsList;
console.log(ContactsListService.contactsList); // prints 'undefined' here
}]);
**JSON file:**
[
{
name: 'Steph Curry',
mobile: '111111111'
},
{
name: 'Lebron James',
mobile: '2323232323'
}
]
我想在控制器中使用来自服务的数据,我无法传递该数据。如果我以不正确的方式注入服务,请纠正我。
谢谢!
您存储的是$http promise,而不是ajax调用的响应。更好的方法是让服务定义一个返回promise的方法,让控制器获得该promise并使用结果。
myApp.service('ContactsListService', function($http) {
this.getContactsList = function() {
return $http.get('js/contacts.json');
};
});
myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
ContactsListService.getContactsList().success(function(data) {
$scope.contacts = data;
});
}]);
谢谢你的回答Joey,我已经试过了,我无法打印成功函数之外的数据:
myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
ContactsListService.getContactsList().success(function(data) {
$scope.contacts = data;
console.log($scope.contacts); // prints data here.
});
console.log($scope.contacts); // prints undefined here.
}]);
只需要知道这是如何进行的。获取数据,然后在处理数据的过程中对其进行处理。
myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
$scope.contacts = []; //initialize it
ContactsListService.getContactsList().success(function(data) {
$scope.contacts = data;
//now do stuff with it
});
//console logging here happens before your async call returns
}]);