您好,一段时间以来,我在使用此 api 调用时遇到了一些问题。当我调用此 API 时,服务中的 console.log 返回我需要的内容,但 Controller 未收到它并返回一个空对象。我想我可能做错了什么,当我返回我的 promise 时,但我找不到问题。我目前正在使用 $q.all() 链接多个获取请求。
这是我的 Controller 功能代码:
$scope.getData = function(input) {
exampleService.getData(input)
.then(function(data) {
console.log(data);
$scope.savedData = data;
}, function(error) {
alert(error); // just sends an alert with -1 if error
});
};
现在这是我的服务功能
this.getData = function(input) {
$q.all([
$http.get(url1),
$http.get(url2)
]).then(function(response) {
console.log(response); //returns array of objects that I want
return response;
});
return $q.all();
};
现在我尝试返回 $q.all().promises 但我的控制台出现错误:
cannot read property 'then' of undefined
我最终想访问数组中每个对象中的一个属性,也就是嵌套在对象中的对象例如
var returnedPromise = [
{dataIDontNeed:1, {dataIwant}},
{dataIDontNeed:2, {dataIwant}},
{dataIDontNeed:3, {dataIwant}}
]
在我发回 promise 之前,我想知道是否有办法从对象数组中获取 dataIwant 对象。如果有人能帮助我,我将不胜感激
最佳答案
您正在返回 $q 的另一个空副本。只需从服务返回原始的 $q.all promise
return $q.all([ $http.get(url1), $http.get(url2) ]);
然后在 Controller 中执行此操作:
service.getData({}).then(...
如果您想转换结果,只需将另一个立即解决的 promise 链接到 all 函数。数据看起来像你说的那样,只需删除你不想要的属性:
return $q.all([ $http.get(url1), $http.get(url2) ]).
then(function(results){
return results.map(function(each){
delete each.dataIDontNeed;
return each;
});
});
在 Controller 中以同样的方式处理它。
关于javascript - $q.all 在服务中返回 Controller 中的空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647753/