Angular 变量为 NaN 或未定义

Angular variable is NaN or undefined

我需要在我的 PlayerComponent class 中组建团队。当我使用这行代码时:

this.teamId = this.player.teamId;

我得到:

"ERROR TypeError: Cannot read property 'teamId' of undefined".

我在 html 中使用此代码从团队对象中检索团队名称。

<p>Team:  {{ team?.name }}</p>

为什么会这样?我的播放器加载正确。

export class PlayerComponent implements OnInit {
  player: Player;
  playerId: number;
  team: Team;
  teamId: number;

  constructor(private playerService: PlayerService, private teameService: TeamService, private alertify: AlertifyService,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.loadPlayer();
    this.loadTeam();
  }

  loadPlayer() {
    this.playerId = this.route.snapshot.params['id'];
    this.playerService.getPlayer(+this.playerId).subscribe((player: Player) => {
      this.player = player;
    }, error => {
      this.alertify.error(error);
    });
  }

  loadTeam() {
    this.teamId = this.player.teamId;
    this.teameService.getTeam(+this.teamId).subscribe((team: Team) => {
      this.team = team;
    }, error => {
      this.alertify.error(error);
    });
  }
}

那是因为您在加载玩家之前加载了团队。请记住,http 请求是异步工作的。

要解决您的问题,您可以将 this.loadTeam() 放入 getPlayer() 函数的订阅中。

export class PlayerComponent implements OnInit {
  player: Player;
  playerId: number;
  team: Team;
  teamId: number;

  constructor(private playerService: PlayerService, private teameService: TeamService, private alertify: AlertifyService,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.loadPlayer();
  }

  loadPlayer() {
    this.playerId = this.route.snapshot.params['id'];


this.playerService.getPlayer(+this.playerId).subscribe((player: Player) => {
      this.player = player;
      this.loadTeam();
    }, error => {
      this.alertify.error(error);
    });
  }

  loadTeam() {
    this.teamId = this.player.teamId;

this.teameService.getTeam(+this.teamId).subscribe((team: Team) => {
      this.team = team;
    }, error => {
      this.alertify.error(error);
    });
  }
}