我想创建一个始终返回从Web服务检索到的factory
对象的json
:
angular.module('test').factory('myService', myService);
myService.$inject = ['$http'];
function myService($http) {
var urlBase;
return {
getContent: function(id) {
return $http.get(urlBase).then(function(response) {
return response.data;
});
}
};
}
当我致电MyService.getContent();
时,我没有收到JSON
个对象,而是收到$$state
和__proto__
的对象。
为什么呢?我怎样才能让工厂直接退回内容?
注意:我知道我可以写
MyService.getContent().then(function(response) {
console.log(response);
});
但这样我在访问工厂时总是要重复then... function
语句。
答案 0 :(得分:2)
您无法返回异步函数的结果。您的return response.data;
语句刚刚退出promise .then()
回调。你应该像这样修改你的功能:
getContent: function(id) {
return $http.get(urlBase);
}
然后像这样称呼它:
MyService.getContent().then(function (response) {
// do something with the response
});
答案 1 :(得分:0)
那是因为你要返回一个已经解决的promise而不是promise实例。刚回来
$http.get(urlBase)
来自你的getContent函数的应该可以解决问题:)