gpt4 book ai didi

javascript - AngularJS 链接 $http get 请求

转载 作者:行者123 更新时间:2023-11-27 23:18:08 24 4
gpt4 key购买 nike

Angular 新手。我试图根据结果调用多个 $http get 调用和第二个调用,并解析第一个调用的 JSON,如下所示:

1) 执行 $http get 请求以获取包含 ["album 1", "album2"] 等元素数组的 JSON

2) 循环数组中的每个项目并执行不同的 $http get 请求以获取该专辑的轨道详细信息。

这是我想要实现此目的的相同(不完整)的 Controller 代码:

    var vm = this;
vm.albums = init;
vm.albums.tracks = albumTracks;
vm.newFunction = newFunction;

return init();

return albumTracks ();

function init(){

$http.get('http://localhost:8080/api/albums').then(function(responseData){
// Parse the json data here and display it in the UI
vm.albums = responseData;
$log.debug(angular.toJson(responseData, true));

// For every album, do another get call in the function albumTracks
for(var i=0; i<vm.albums.length; i++){
vm.albums.tracks = [];
vm.albums.tracks.push(albumTracks(vm.albums[i]));
console.log(vm.albums.tracks); // This prints on the console as [undefined]
}

console.log(vm.albums.tracks);
return vm.albums;
})
}

function albumTracks(album){
$http.get('http://localhost:8080/api/albums/'+album).success(function(trackResponse){
//parse each album and get the track list
vm.albums.tracks = trackResponse;
return vm.albums.tracks;
})
}

以下是每个 JSON 响应的样子:

//http://localhost:8080/api/albums/:
[
"the-revenant-original-motion-picture-soundtrack",
"twilight-of-the-ghosts"
]

//http://localhost:8080/api/albums/twilight-of-the-ghosts:
[
{
"fileName": "twilight-of-the-ghosts-twilight-of-the-ghosts-01-pinned-to-the-mattress.flac",
"title": "Pinned to the Mattress",
"artists": "Twilight of the Ghosts",
"album": "Twilight of the Ghosts",
"sequenceNumber": 1,
"trackLength": 274
},
{
"fileName": "twilight-of-the-ghosts-twilight-of-the-ghosts-02-sinking-slowly-slowly-sinking.flac",
"title": "Sinking Slowly Slowly Sinking",
"artists": "Twilight of the Ghosts",
"album": "Twilight of the Ghosts",
"sequenceNumber": 2,
"trackLength": 270
}
and so on

最佳答案

目前,您将使用每个 tracksResponse 覆盖 tracks。您可能想做:

vm.album.tracks = vm.album.tracks.concat(trackResponse);

相反,您想要关联专辑和轨道,因此请使用专辑对象数组而不是字符串数组:

vm.albums = responseData.map(album => ({name: album, tracks: []}));

然后,您将传入专辑对象,您可以在轨道请求后更新该对象:

album.tracks = trackResponse;

console.log 在您拥有它们的地方无法工作,因为 $http异步

let a = "a";
$http.get(() => a = "b");
console.log(a); // logs "a" even though it was written after `a = "b"`

这意味着,如果您依赖 $http 请求的响应来执行任何操作,则必须在请求的回调中执行该操作。不过,在这种情况下您可能不需要这样做,因为由于 Angular 的工作原理,更新 vm 应该会自动更新您的模板。

关于javascript - AngularJS 链接 $http get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com