为什么订阅服务后 value 未定义?

Why is value undefined after subscribing to a service?

我正在订阅一项服务以从 json 文件中获取单个对象。然后我想根据某个键的值对该对象进行排序。如果我尝试引用返回的对象,我会收到未定义的错误。

示例:

ngOnInit() {
    this.teamName = this.route.snapshot.paramMap.get('team').toLowerCase();
    this.currAge = this.route.snapshot.paramMap.get('age').toLowerCase();
    this.currDiv = this.route.snapshot.paramMap.get('division').toLowerCase();
    this.getTeam(this.currAge, this.currDiv, this.teamName);
    this.sortTournaments();
  }
  getTeam(age: string, gender: string, teamName: string): void {
    this.standingService.getTeam(age, gender, teamName).subscribe({
      next: team => this.currTeam = team,
      error: err => this.errorMessage = err
    });
  }
  sortTournaments(): void{
    this.currTeam.past_tournaments.sort(function(a,b){
      return a.year - b.year;
    })
  }

我意识到问题是 getTeam() 是异步的,但我该如何解决这个问题?

选项 1: 设置值后,只需在 Observers next 方法中调用 this.sortTournaments()

next: team => { 
  this.currTeam = team;
  this.sortTournaments();
},

选项 2: 将 Observable 变成一个 promise,比如

this.standingService.getTeam(age, gender, teamName).toPromise()
  .then(team => this.currTeam = team)
  .then(() => this.sortTournaments())
  .catch(err => this.errorMessage = err)