我目前正在使用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行中丢弃了错误。
谢谢您的帮助!
http获取请求是异步调用的,因此在这种情况下,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>
问题在这里:
nextQuestion() {
this.questionService.getQuestion().subscribe(data => {
// Put debugger to check the value for games.
debugger
this.games = data;
});
}
首先检查数据是数据从服务器返回到您的 getQuestion 是正确的,并且预计它根本不会出现,然后使用调试器检查,您可以看到分配给游戏的值以获取更多信息调查,否则将游戏设置为默认值,当数据出现在订户中时,它将更改。
如果正确分配了游戏,但是玩家是可选的,则在您的html
中使用它[innerText]="games?.player"