如何在其他组件中触发变更检测?

时间:2018-08-21 00:57:50

标签: angular

当我从锦标赛中添加/删除比赛时,表格不会更新。我了解这是因为teams尚未更新,但是它们下面带有matches的数组已更新。我知道您使用ChangeDetectorRef来更新组件,但是如何告诉另一个组件detectChanges()

我有一张带有服务的团队地图,上面附有游戏。

export class TournamentMatchesService {
  teams: Array<Team> = [];
}

export class Team {
    matches: Array<Match> = [];
}

我有一个添加和删除匹配项的组件

export class AddMatchComponent implements OnInit {

  matches: Array<Match>;

  constructor(private tournamentMatchesService: TournamentMatchesService, private cdr: ChangeDetectorRef) { }

  ngOnInit() {

  }

  addGameToTournament(match: Match) {
    this.tournamentMatchesService.addMatch(match);
    match.included = true;
    this.cdr.detectChanges();
  }

  removeGameFromTournament(match: Match) {
    this.tournamentMatchesService.removeMatch(match);
    match.included = false;
    this.cdr.detectChanges();
  }
}

和一个显示它们的

export class TournamentResultsComponent implements OnInit {

  constructor(private tournamentMatchesService: TournamentMatchesService, 
    private cdr: ChangeDetectorRef) { }

  ngOnInit() { }

  sortData(sort: Sort) {
    this.tournamentMatchesService.sort(sort);
    this.cdr.detectChanges();
  }
}

// html文件

  <table class="mat-elevation-z8" style="width:80%" (matSortChange)="sortData($event)" matSort>
    <tr>
      ...tableHeader
    </tr>
    <tr *ngFor="let team of this.tournamentMatchesService.teams">
      ...tableBody
    </tr>
  </table>

1 个答案:

答案 0 :(得分:2)

正如杰森·怀特(Jason White)所建议的那样,最好使用BehaviorSubject并订阅组件中的更改,如下所示:

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export class TournamentMatchesService {
  teams$ = new BehaviorSubject<Team[]>([]);

  getTeams(): Observable<Team[]> {
    return this.teams$;
  }
}

然后在您的组件中:

export class TournamentResultsComponent implements OnInit {

  constructor(private tournamentMatchesService: TournamentMatchesService, 
    private cdr: ChangeDetectorRef) {
      this.tournamentMatchesService.getTeams().subscribe(val => {
        this.cdr.detectChanges();
      })
    }

  ngOnInit() { }

  sortData(sort: Sort) {
    this.tournamentMatchesService.sort(sort);
    this.cdr.detectChanges();
  }
}