为大型数据集优化* ngFor循环和* ngIf(Angular 2)

时间:2017-09-11 22:38:34

标签: angular

我正在使用* ngFor显示数据JSON数据(来自API),我有点担心我的方法中可能出现的性能问题。所以我正在寻找有关如何改进它的建议。

这是我在页面中显示的JSON结构(没有数据):https://gist.github.com/fogofogo/f4b5ac9a765fc684e7e08b30221c6419

这是具有完整数据的JSON结构:https://gist.github.com/fogofogo/f7b5c3db347246689ea5007344eff53b

JSON只显示两场比赛的数据,而且已经是2k线!它可能有100场比赛。

这就是我用来在页面上显示数据的方法:

<div class="..." *ngFor="let sport of competition.sports">

  <p>{{ sport.sport }}</p>

  <ng-container *ngFor="let country of sport.countries">

    <div class="..." *ngFor="let tournament of country.tournaments">

      <p>{{ country.country }} - {{ tournament.tournament }}</p>

      <div class="..." *ngFor="let fixture of tournament.fixtures" class="tournament_item">

        <p>{{fixture.homeTeam.name}} V {{fixture.awayTeam.name}}</p>

        <ng-container *ngFor="let market of fixture.markets">

          <ng-container *ngIf="market.marketId === 1">

            <div class="..."  *ngFor="let marketOption of market.marketOptions">
          {{ marketOption.fractionOdds }}
            </div>

          </ng-container>

        </ng-container>

      </div>

    </div>

  </ng-container>

</div>

我从控制器那里得到数据:

ngOnInit() {
 this.sub = this.route.params.subscribe(params => {
   this.id = params['competitionId'];
   this.service.get(this.id)
  .subscribe(competition => this.competition = competition)
});
}

除了非常多的ngFors(感觉不对)之外,我特别关注这个*ngIf="market.marketId === 1"。我需要在100场比赛中检查20多个市场。当我在250个匹配的浏览器中运行此代码时,加载大约需要5秒钟。

如果有人能就如何优化这一点提出一些建议,我将不胜感激。对于上面任何明显的问题道歉 - 在这里有角度的2/4新人。

1 个答案:

答案 0 :(得分:0)

我建议将其分解为更简单的元素。

看起来你正在构建一个元素来管理整个树。如果你把它分成几个部分,那么构建更大的结构会更容易。

所以你有一个显示单一市场选择的组件。然后是一个选项集合组件,用于重复一系列市场选项。然后是锦标赛组件......以及向外。

它可能变得非常大,但如果这是数据的本质,那就是数据的本质。

一旦你有了结构化,过滤数据以显示所需的代码应该变得有些明显。