AngularJS链接$http获取请求

AngularJS chaining $http get requests

本文关键字:获取 请求 http 链接 AngularJS      更新时间:2023-09-26

新到角度。我正在尝试调用多个$http获取调用和第二个调用,具体取决于结果和解析的第一个 JSON 如下:

1) 执行一个 $http get 请求以获取带有 ["专辑 1"、"专辑 2"] 等元素数组的 JSON

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

目前您将用每个tracksResponse覆盖tracks。您可能希望执行以下操作:

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

相反,您希望关联专辑和曲目,因此请为专辑使用对象数组而不是字符串数组:

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

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

album.tracks = trackResponse;

console.log s 在您拥有它们的地方不起作用$http因为它是异步的

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

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

根据我的知识,您可能需要角度循环而不是"for"循环 您可以在其中附加跟踪器而无需更多编码和混乱。

vm.albumsWithTrackers = []; // New Variable Defining needed.
//http://localhost:8080/api/albums/: // it is fine Json but with some define attributes it looks good 
                 [
                  "the-revenant-original-motion-picture-soundtrack",
                  "twilight-of-the-ghosts"
                 ]
      //  Albums With attributes Defined :- 
        [
          "id":"the-revenant-original-motion-picture-soundtrack",
          "id":"twilight-of-the-ghosts"
         ]
        angular.forEach(vm.albums, function (album, key) {
                    album.tracks.push(albumTracks(album));  // attaching only trackers to current album on loop 
                    vm.albumsWithTrackers.push(album); // pushing Album to new defined variable
                    console.log(album.tracks);  
                    });
                });
               console.log(vm.albumsWithTrackers);//album with attached trackers.
            return vm.albumsWithTrackers;
    function albumTracks(album){
            $http.get('http://localhost:8080/api/albums/'+album.id).success(function(trackResponse){
                 return trackResponse; //send trackers response directly
            })
        }

我希望这种方法将有助于解决您的问题:-)谢谢。