【问题标题】:Angular 'For loop' not displaying in order角度“For循环”未按顺序显示
【发布时间】:2017-03-23 19:33:06
【问题描述】:

从 'AngularJS' 中的 api 调用数据并在 for 循环中使用 for 循环来执行。我在控制台中期待的结果是:

'赛季编号' “剧集名称” “剧集名称”

'赛季编号' “剧集名称” “剧集名称”....

但是在谷歌浏览器控制台上输出的结果是

“季号”“季号”“季号”

然后是所有剧集的名称。

我的循环可能看错了或遗漏了一些东西。但它真的困扰着我。任何帮助将不胜感激

    var season_number = 0;
    tvSeasonDetails = seasondetails;
    console.log(tvSeasonDetails);

    for (var i = 0; i < tvSeasonDetails.length; i++) {
      season_number = tvSeasonDetails[i].season_number;
      console.log(season_number);
      var url = 'https://api.themoviedb.org/3/tv/' + tvID + '/season/' + season_number + '?api_key=7baae7b093159f1876fbe91176adcb32'; // generating the url
      $http({
          method: 'GET',
          url: url

        })
        .then(function(response) {
          for (var ii = 0; ii < response.data.episodes.length; ii++) {
            console.log(response.data.episodes[ii].name);
          }

        })
    }

编辑:使用 AngularJS 在 HTML 页面上显示结果。理想情况下,我想做的是显示:

第 1 季:

'剧集名称'

'剧集名称'

'剧集名称'

第 2 季:

'剧集名称'

'剧集名称'

'剧集名称'...等等

每次都需要更改网址以显示每个季节的剧集。

【问题讨论】:

标签: javascript angularjs api for-loop ionic-framework


【解决方案1】:

内部循环是异步调用的——所以在 http get 请求被解决之前它不会执行。 $http.get 函数不会等待请求完成。它只是继续循环。这就是为什么所有console.log(season_number); 消息首先出现,console.log(response.data.episodes[ii].name) 紧随其后(也以不确定的顺序)。

更新

在不确切知道您希望如何表示数据的情况下,我将尝试为您提供一个可以构建的示例。

tvSeasonDetails = seasondetails;

var promises = {};
angular.forEach(tvSeasonDetails, function(tvSeason){
    promises[tvSeason.season_number] = $http.get('https://api.themoviedb.org/3/tv/' + tvID + '/season/' + tvSeason.season_number + '?api_key=7baae7b093159f1876fbe91176adcb32');
});

$scope.episodeData = [];
$q.all(promises).then(function(episodesBySeasonNumber){
    angular.forEach(episodesBySeasonNumber, function(response){
        // You should replace this, with whichever method you want to save your data to the scope.
        $scope.episodeData.push(response.data);
    });
});

那么在你看来:

<ul>
    <li ng-repeat="season in episodeData">{{season.name}}
        <ul>
            <li ng-repeat="episode in season.episodes">{{episode.name}}</li>
        </ul>
    </li>
<ul>

我决定使用$q.all,以便在将数据添加到 $scope 之前等待所有季节都被检索到。它还具有一个简洁的功能,即响应以与数组中的承诺相同的顺序返回。

更新 2

添加了plunker with a working example

注意:您可能应该在此之后替换您的 API 密钥

【讨论】:

  • 移动 console.log(season_number);在 .then() 内
  • 这不起作用,因为season_number 绑定到外部范围,因此最后分配的season_number 将出现在每次调用console.log(season_number); 内部.then()
  • 谢谢,正是我要找的东西
猜你喜欢
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多