我有一个服务将对象数组返回给控制器,即控制台 显示以下回复:
Array[0]
0
:
Object
first_name
:
"Emi"
id
:
"255860959988416847"
last_name
:
"Hauritz Seino"
url
:
"https://www.pinterest.com/amusemi/"
__proto__
:
Object
1
:
Object
first_name
:
"mohammed"
id
:
"474848491869398608"
last_name
:
"al-kahtani"
url
:
"https://www.pinterest.com/alkahtani0848/"
__proto__
:
Object
2
:
Object
first_name
:
"❤ T r e n d 2 W e a r ❤ "
id
:
"418553496527224475"
last_name
:
""
url
:
"https://www.pinterest.com/trend2wear/"
__proto__
:
Object
length
:
3
__proto__
:
Array[0]
我需要帮助来理解当数组中有三个对象时数组显示“0”长度的方式,以及如何从控制器中访问这些对象。
控制器代码:
$http.get('json/ConfigData.json').success(function(data) {
$scope.ebayApiURL = data.ebay.BeautyebayPopularItems;
var parampins= 'PinsByBoard';
var paramApiURL='PinsByBoardByTokenAPIURL'
arrpins=data.Pinterest[parampins];
arrapiurl =data.Pinterest[paramApiURL];
console.log(arrapiurl);
console.log(arrpins);
$scope.UrlArr=[];
for(var i=0; i<data.Pinterest[parampins].length ;i++)
{
var PinFullUrl=arrapiurl + arrpins[i] + data.Pinterest.PiNJSONCALLBACKByToken;
console.log(PinFullUrl);
$scope.UrlArr[i]=PinFullUrl;
}
$scope.Creator=[];
$scope.Creator=Comics.LoadDataFromPinteByToken($scope.UrlArr);
console.log($scope.Creator);
})
服务代码:
var deferred = $q.defer();
var urlCalls = [];
var mergedArray =[];
var k=0;
angular.forEach(UrLArray, function(url)
{
urlCalls.push($http.jsonp(url));
});
$q.all(urlCalls)
.then(function(results) {
deferred.resolve(
JSON.stringify(results.length))
console.log(results);
for(i=0;i<results.length;++i)
mergedArray[i]=results[i].data.data.creator;
},
function(errors) {
deferred.reject(errors);
},
function(updates) {
deferred.update(updates);
}
)
return mergedArray;
}
答案 0 :(得分:1)
你必须像服务这样
返回服务中的承诺var deferred = $q.defer();
var urlCalls = [];
var mergedArray =[];
var k=0;
angular.forEach(UrLArray, function(url)
{
urlCalls.push($http.jsonp(url));
});
$q.all(urlCalls)
.then(function(results) {
deferred.resolve(
JSON.stringify(results.length))
console.log(results);
for(i=0;i<results.length;++i)
mergedArray[i]=results[i].data.data.creator;
})
return deferred.promise; // return the promise
}
// and use then within controller
// like : service.getData().then(function(resolved_data){
//console.log(resolved_data)
//})