我正在尝试一些angularjs的东西。所以我有一些数组。其中一位是艺术家。这是console.log(artists);
问题是我无法单独访问数组的元素。我读了很多关于关联数组的事情,可能会对SO提出问题,但没有一个真的有帮助。所以,无论是我犯的是一个非常愚蠢的错误,还是其他一些事情。
我在每个阵列中得到的结果很少。
console.log(artists[0]); //returns undefined
console.log(artists['0']); //returns undefined
console.log(artists.length); // returns 0 in spite of the fact it showed 20 previously
console.log(Array.isArray(artists)); //returns true
是的,我在服务中创建了这样的数组,ChartService
var artists = [];
var artistids = [];
var tracks = [];
$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
var items = data.artists.items;
items.forEach(function(item){
artists.push(item.name);
artistids.push(item.id);
var query = trackApi+item.id+'/top-tracks?country=SE'
$http.get(query).success(function (response) {
tracks.push({'preview': response.tracks[0].preview_url});
});
});
});
return {
Artists : artists,
Tracks : tracks
}
我的控制器
console.log(ChartService.Artists); //runs fine
console.log(ChartService.Tracks); //runs fine
$scope.tracks = ChartService.Tracks;
console.log($scope.tracks); //runs fine
console.log($scope.tracks[0]); //returns undefined
console.log($scope.tracks['0']); //returns undefined
console.log($scope.tracks.length); // returns 0 in spite of the fact it showed 20 previously
console.log(Array.isArray($scope.tracks)); //returns true
答案 0 :(得分:0)
问题是您在发出的http get请求触发了他们的回复之前检查了artists
的内容。
解决这个问题的一种方法是将代码置于success
回调中,如下所示:
$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
var items = data.artists.items;
items.forEach(function(item){
artists.push(item.name);
artistids.push(item.id);
var query = trackApi+item.id+'/top-tracks?country=SE'
$http.get(query).success(function (response) {
tracks.push({'preview': response.tracks[0].preview_url});
});
});
// here
console.log(artists);
});
仍然,这解决了artists
,但如果你需要tracks
,你需要做类似的事情:因为你有多个请求提供,你需要检查tracks
数组的长度,并且只有它具有完整的长度,如下所示:
$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
var items = data.artists.items;
items.forEach(function(item){
artists.push(item.name);
artistids.push(item.id);
var query = trackApi+item.id+'/top-tracks?country=SE'
$http.get(query).success(function (response) {
tracks.push({'preview': response.tracks[0].preview_url});
if (tracks.length == items.length) { // all done
console.log(artists, tracks);
}
});
});
});
在后续问题(评论中)中,您解释说您需要在控制器中使用此功能。您可以查看$watch
或该方法的变体。如果您需要帮助,我建议您提出一个新问题。