gpt4 book ai didi

AngularJS - 如何在嵌套 http.get 请求的情况下返回对象

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:29:30 26 4
gpt4 key购买 nike

我在使用 AngularJS 时遇到一个问题,我无法在 $http.get 方法中为外部变量赋值。这是我的代码片段:

.factory('MediaService',['$http', function($http, $q){
return {
getGalleryIds : function() {
galeriURL = 'http://api.tika.gov.tr/www/tr/galleries?';
return $http.get(galeriURL, { cache: true}).then(function(response){
contentIdList = response.data.data;
var contentList = [];
for (i=0;i<contentIdList.length;i++) {
var galeriContentURL = 'http://api.tika.gov.tr/www/tr/galleries/' + contentIdList[i].id;
contentList[i] = $http.get(galeriContentURL, { cache: true})
.then(function(response){
return response.data;
});
}
console.log(contentList);
return contentList;
});
}
}
}]);

我的问题是在 console.log(contentList); 行我得到了 Promise Array 因为我不能给外部变量赋值。

[Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise]

如何在 for 循环 $$http.getconsole.log(contentList) 行中为 var contentList = [ ]; 变量赋值; 得到Object Array如下

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

最佳答案

问题出在这部分:

contentList[i] = $http.get(galeriContentURL, { cache: true})
.then(function(response){
return response.data;
});

$http returns a promise which you are storing in contentList array, and not the data., when you use a return inside the success function, the data will not be returned to content list.


您需要用以下代码替换该代码:

 $http.get(galeriContentURL, { cache: true})
.then(function(response){
contentList[i] = response.data;
});

This does not eally guarantee that all the data objects stored in array will be in the same order as the order in which they are requested.

关于AngularJS - 如何在嵌套 http.get 请求的情况下返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28558697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com