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

AngularJS-如何在嵌套http.get请求的情况下返回对象,angularjs,http,get,angularjs-service,angular-promise,Angularjs,Http,Get,Angularjs Service,Angular Promise,AngularJS的一个问题是,我无法为$http.get方法中的外部变量赋值。以下是我的代码片段: .factory('MediaService',['$http', function($http, $q){ return { getGalleryIds : function() { galeriURL = 'http://api.tika.gov.tr/www/tr/galleries?'; return $http.g

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;
            });
        }
    }
}]);
如何为var contentList=[]赋值;for循环$$http.get中的变量,位于console.logcontentList行;获取对象数组,如下所示

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

问题在于这一部分:

contentList[i] = $http.get(galeriContentURL, { cache: true})
                        .then(function(response){
                            return response.data;
                        });
$http返回存储在contentList中的承诺 数组,而不是数据,当您在成功内部使用返回时 函数,则数据不会返回到内容列表

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

 $http.get(galeriContentURL, { cache: true})
                        .then(function(response){
                            contentList[i] = response.data;
                        });
这并不能真正保证存储在中的所有数据对象 数组的顺序将与它们的排列顺序相同 请求


感谢您的回答,但这对我不起作用,因为在line console.logcontentList;我得到一个空数组。在控制台返回之前,我读取的是[]而不是[Object,Object]。@ozhani::是的,那么从该url返回数据时还有一些其他问题。您可以在自己的函数中尝试console.logresponse吗?不,url中的数据没有问题。当我使用console.log作为http.get.then{console.log}时,我得到的是对象。同样,如果我像所讨论的那样填充contentList,我得到的是承诺,但我需要对象Promise@ozhanli承诺将始终由$http返回:请尝试此contentList.pushresponse;,而不是contentList[i]=response.data;在我的回答中,应该是:
 $http.get(galeriContentURL, { cache: true})
                        .then(function(response){
                            contentList[i] = response.data;
                        });