访问对象的属性我创建了.factory简单AngularJS服务()称为$的getUser从users.json获取数据:我无法从.factory AngularJS 1.6
{
"john": {
"name": "John",
"address": "New York"
},
"bob": {
"name": "Bob",
"address": "Boston"
}
}
现在我想在mainController使用此数据:
angular.module('myApp', [])
.factory('$getUser', ['$http', function($http){
var users = {};
$http.get('users.json').then(
function(response) {
users.data = response.data;
}
);
return users;
}])
.controller('mainController', ['$getUser', function($getUser){
// I can access whole $getUser object
console.log($getUser);
// but when I want to access $getUser.data it gives me 'undefined'
console.log($getUser.data);
}]);
当我想console整个$的getUser对象,它的工作原理,但我无法访问$ getUser.data属性。为什么?
在我猜测,你不需要使用'data'对象。因为可能你的工厂没有数据对象。 –
可能的重复[如何返回来自异步调用的响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Erazihel
[AngularJS 1.X中的异步调用如何工作? $ Http调用不返回值](https://stackoverflow.com/questions/31548385/how-does-asynchronous-call-work-in-angularjs-1-x-http-call-not-returning-value) –