网站搜索

angular - 类型错误:无法读取未定义的属性 'player'


我目前正在使用 Angular 开发一个项目。由于我对编程还比较陌生,我不知道该如何处理这个错误:

TypeError: Cannot read property 'player' of undefined. 

基本上我不知道在哪里以及如何定义这个属性。以下是我正在使用的代码:

我的 game.component.html:

<div class="container">
 <div class="playerBox">
  <table>
    <tr>
      <td class="player">Player: </td>
      <td class="player" [innerText]="games.player"></td>
    </tr>
    <tr>
      <td class="player">Round: </td>
      <td class="player" [innerText]="games.round"></td>
    </tr>
  </table>
 </div>
 <div class="content">
  <p [innerText]="games.question"></p>
  <button class="button" (click)="nextQuestion()">Next</button>
  <button class="button" routerLink="/home">Home</button>
 </div>
</div>

Game.component.ts:

import { Component, OnInit } from '@angular/core';
import { QuestionService } from '../../services/question.service';
import { Game } from "../../models/game";

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.sass']
})
export class GameComponent implements OnInit {

  games: Game;

  constructor(private questionService: QuestionService) { }

  ngOnInit() {
    this.nextQuestion();
  }

  nextQuestion() {
    this.questionService.getQuestion().subscribe(data => {
      this.games = data;
    });
  }

}

Question.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { O`enter code here`bservable } from 'rxjs';
import { Game } from '../models/game';

@Injectable({
  providedIn: 'root'
})
export class QuestionService {

  constructor(private http: HttpClient) { }


  /* Get question from DB */
  getQuestion(): Observable<Game> {
    return this.http.get<Game>("//localhost:8443/api/next");
  }

  resetAll() {
    return this.http.get("//localhost:8443/api/reset");
  }

}

最后是 Game.ts:

export class Game {
  player: string;
  round: number;
  question: string;
}

错误出现在 game.component.html 的第 6 行。
感谢您的任何帮助!

答案#1

HTTP GET 请求是异步调用,所以在这种情况下,games 在获取值之前会是未定义的,尝试为 games 属性设置初始值

 games: Game = new Game();

另一种方法是使用 ?.(安全导航操作符)

<table>
    <tr>
      <td class="player">Player: </td>
      <td class="player" [innerText]="games?.player"></td>
    </tr>
    <tr>
      <td class="player">Round: </td>
      <td class="player" [innerText]="games?.round"></td>
    </tr>
  </table>

答案#2

问题在这里:

nextQuestion() {
    this.questionService.getQuestion().subscribe(data => {
         // Put debugger to check the value for games.
         debugger
         this.games = data;
    });
  }

首先检查从服务器返回到你的 getQuestion 的数据是否正确,如果预期的数据根本没有返回,那么使用调试器检查,你可以看到分配给 games 的值以便进一步调查,否则为 game 设置默认值,当数据到达订阅者时,它将被更改。

如果游戏被正确分配但玩家是可选的,那么在你的 HTML 中可以这样使用它

[innerText]="games?.player"