Новый угловой. Я пытаюсь вызвать несколько вызовов $ http get и второй вызов в зависимости от результата и проанализировал JSON первого из них следующим образом:
1) Сделайте запрос $ http get, чтобы получить JSON с массивом таких элементов, как ["album 1", "album2"]
2) Прокрутите каждый элемент массива и выполните другой запрос $ http get, чтобы получить информацию о треке для этого альбома.
Вот код контроллера для того же самого (неполные), где я хочу, чтобы достичь этого:
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
Спасибо. Вы также предполагаете, что я удаляю цикл, который у меня есть? Я немного потерялся там. Как я должен использовать http.get (....). Then (function() еще один http get()) и т. Д.? – noobcoder
@noobcoder нет, петля в порядке. Вы можете делать эти HTTP-запросы одновременно, поэтому асинхронность здесь полезная. –
Еще раз спасибо. Я не думаю, что понимаю синтаксис responseData.map (альбом => ({имя: альбом, треки: []})); The => непонятно для меня. Это то, как мы создаем объект карты в угловом? – noobcoder