如何从$ q.all(promises)中检索数据?

时间:2016-03-16 22:40:10

标签: angularjs promise angular-promise

我有以下函数,我在数组中推送所有promises然后使用then函数,我的意思是通过promises sevserse并获取每个promise都有的数据数组(该服务返回jsons数组)

     var getPP= function(){
                        var promises = [];
                        angular.forEach($scope.myObjects, function(myObject) {

                            var urlPath = <someurl>+myObject.name;
                            var promise = $http({
                                url   : urlPath,
                                method: 'GET'
                            });
                            promises.push(promise);
                        });

                        $q.all(promises).then(function(data){
                            for(j=0; j < data.length; j++){
                                var jsonArray= [];
                                console.log('response = '+data[j]+' and j = '+j);--> 

**this log statement just prints a [object object] 
        even though the json array is pretty huge as returned by the service. What are these two objects?**

                                for (k = 0; k < data[j].length; k++) { 

    **--> It never gets here and does not logs anything below**
                                   console.log('inside loop'); 
                                   console.log(data[j][k].id+data[j][k].empname);
                                }
                           }
                       });

我是否正确检索数据?我们如何做到这一点的任何输入? 请阅读代码中的两条注释,了解我所面临的问题。

谢谢!

编辑1 - json看起来像这样 -

[{
    "id": 1,
    "empname": "emp1"
},
{
    "id": 2,
    "empname": "emp2"
},
{
    "id": 3,
    "empname": "emp3"
}]

编辑2:我也尝试更改我的promise变量定义,如下所示,但同样的问题

 var promise = $http({
                    url   : urlPath,
                    method: 'GET'
                }).success(function(data, status){
                    defer.resolve(data);
                })
                    .error(function(data, status) {
                        defer.reject(status);
                    });

编辑3:根据您的建议并使用EDIT 2 promise变量格式 - 以下是我使用以下两个控制台语句时控制台中的输出:

console.log('response ='+ JSON.stringify(data [j])+'和j ='+ j);

控制台输出:

response = {"data":[{"id": 1,"empname": "emp1"},{"id": 2,"empname": "emp2"},{"id": 3,"empname": "emp3"}],"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://localhost:8091/api/types?isoCode=USA&groupName=AdvisorySpeedLimit2_40","headers":{"Accept":"application/json, text/plain, */*","X-Requested-With":"XMLHttpRequest"},"requestTimestamp":1458169519915,"responseTimestamp":1458169520190},"statusText":"OK"}

1 个答案:

答案 0 :(得分:0)

感谢@Bergi的所有建议!

data[j].data[k]完成了诀窍并显示了正确的数据。