我想将 $http.get 的结果从我的服务发送到我的 Controller 。
我的服务示例.js
function messagesService($q,$http){
var messages;
$http({
method: 'GET',
url: 'http://api.com/feedback/list'
})
.then(function success(response){
messages = response.data;
console.log(messages);
},function error(response){
console.log('error'+ response);
});
console.log(messages);
return {
loadAllItems : function() {
return $q.when(messages);
}
};
}
})();
我的 Controller 示例.js
function MessagesController(messagesService) {
var vm = this;
vm.messages = [];
messagesService
.loadAllItems()
.then(function(messages) {
console.log(messages);
vm.messages = [].concat(messages);
});
}
})();
上面的代码结果给出了未定义的输出。 我想念什么?
最佳答案
$q.when
对象确实期望 promise/object
使其工作。在您的情况下,您必须在 $http.get
调用时将 promise
对象传递给 $q.when
。这里的 messages
对象不持有 $http.get
的 promise ,因此您可以像下面这样更改方法的实现。
服务
function messagesService($q,$http){
var messages = $http({
method: 'GET',
url: 'http://api.com/feedback/list'
})
.then(function success(response){
return response.data;
},function error(response){
return $q.reject('Error Occured.');
});
return {
loadAllItems : function() {
return $q.when(messages);
}
};
}
然后 Controller 将解决该 promise & .then
将完成任务
function MessagesController(messagesService) {
var vm = this;
vm.messages = [];
messagesService
.loadAllItems()
.then(function(messages) {
console.log(messages);
vm.messages = [].concat(messages);
});
}
Note: Using
$q
to create a custom promise, is considered as bad pattern when you have$http.get
method there(which does return promise itself)
改进实现
function messagesService($q, $http) {
var messages, getList = function() {
return $http({
method: 'GET',
url: 'http://api.com/feedback/list'
})
.then(function success(response) {
messages = response.data
return response.data;
}, function error(response) {
return $q.reject('Error Occured.');
});
};
return {
loadAllItems: function() {
if (!data)
return getList(); //return promise
else
return $q.resolve(messages); //return data
}
};
};
关于javascript - 使用服务的输出到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374284/