我目前正在使用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行中引发了错误。
谢谢您的帮助!
答案 0 :(得分:2)
问题在这里:
nextQuestion() {
this.questionService.getQuestion().subscribe(data => {
// Put debugger to check the value for games.
debugger
this.games = data;
});
}
首先检查是否有数据从服务器返回到您的 getQuestion 是正确的,并且预期根本不会出现,然后通过调试器检查,您可以查看分配给游戏的值,以了解更多信息调查,否则设置游戏的默认值,则当用户输入数据时,它将被更改。
如果游戏分配正确,但玩家是可选的,则可以在HTML [innerText] =“ games?.player”
中使用它答案 1 :(得分:2)
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>