【问题标题】:AngularJS - How to return object in case nested http.get requestAngularJS - 如何在嵌套 http.get 请求的情况下返回对象
【发布时间】:2015-04-17 23:36:03
【问题描述】:

我对 AngularJS 的一个问题是,我无法在 $http.get 方法中为外部变量赋值。这是我的代码 sn-p:

.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 loop $$http.get 和行 console.log(contentList) 中为 var contentList = [ ]; 变量赋值; 得到对象数组如下

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

【问题讨论】:

    标签: angularjs http get angularjs-service angular-promise


    【解决方案1】:

    问题出在这部分:

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

    $http 返回一个 promise,您将其存储在 contentList 数组,而不是数据。,当您在成功内使用返回时 函数,数据不会返回到内容列表中。


    您需要用以下代码替换该代码:
     $http.get(galeriContentURL, { cache: true})
                            .then(function(response){
                                contentList[i] = response.data;
                            });
    

    这并不能保证所有数据对象都存储在 数组的顺序与它们的顺序相同 请求。

    【讨论】:

    • 感谢您的回答,但这对我不起作用,因为在行 console.log(contentList); 我得到一个空数组。在控制台返回之前,我正在阅读 [ ] 而不是 [Object,Object]
    • @ozhanli:: 是的,那么当您从该 url 返回数据时还有其他问题。你能在你的then()函数中试试console.log(response)
    • 不,来自 url 的数据没有问题。当我使用 console.log 作为 http.get().then(){console.log} 我得到对象。
    • 另外,如果我按照问题填充 contentList,我会得到承诺,但我需要 Object 而不是 Promise
    • @ozhanli promise 将始终由$http 返回:试试这个contentList.push(response);,而不是我的回答中的contentList[i] = response.data;,应该可以工作:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多