角度变量为NaN或未定义

时间:2018-11-12 14:11:01

标签: angular variables undefined

我需要让团队加入我的PlayerComponent类。当我使用以下代码行时:

this.teamId = this.player.teamId;

我收到“错误TypeError:无法读取未定义的属性'teamId'”。

我在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);
    });
  }
}

1 个答案:

答案 0 :(得分:0)

那是因为您在加载球员之前先加载了团队。请记住,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);
    });
  }
}
相关问题