Angular 如何正确获取类元素?
我有一个关于从API获取类元素的小问题。我的班级是这样的Angular 如何正确获取类元素?,angular,typescript,Angular,Typescript,我有一个关于从API获取类元素的小问题。我的班级是这样的 export class Game { count:number; next:string; previous:string; public results = new class { game_id:number; title:string; } } 在ts文件中,我喜欢 games: Game[] //to have a variable called games which
export class Game {
count:number;
next:string;
previous:string;
public results = new class {
game_id:number;
title:string;
}
}
在ts文件中,我喜欢
games: Game[] //to have a variable called games which belongs to game class
ngOnInit() {
//with the func below, I subscribe the data that comes from API
this.gameService.getGames().subscribe(data => {
this.games = data
})
}
在html文件中,我需要访问游戏向量的结果部分,因为这部分是我需要查找的部分。这是我的html代码
<div *ngFor="let g of games.result"> <!-- Since the result part should be in a loop -->
<div class="card-body">
<h5 class="card-title">{{g.title}}</h5>
<p class="card-text">{{g.game_id}}</p>
</div>
</div>
尝试:
{{r.title}}
{{r.game\u id}
或者,如果你只是一个游戏:
<div *ngFor="let r of games[0].results">
<div class="card-body">
<h5 class="card-title">{{r.title}}</h5>
<p class="card-text">{{r.game_id}}</p>
</div>
</div>
{{r.title}}
{{r.game\u id}
{{g?.title}
{{{g?.game_id}
解析HTML中的对象时,始终尝试使用
?
。这是一张安全支票,因此,在访问变量之前,请检查变量是否已定义。我已经尝试过了,但是我得到了另一个关于NGO的错误,即它只能将数组之类的不可写入项添加到您从服务器获得的问题部分。游戏数据。我已经编辑了问题并共享了我订阅的数据。我已经尝试过了事实上,它部分起作用。现在我在浏览器控制台上没有收到任何错误消息,但我在visual studio代码终端上收到一些错误消息,上面说:“src/app/games/games.component.html:49:39-error TS2339:Property'results'在类型Game[]上不存在。”。但由于某些原因,它现在无法编译://
<div *ngFor="let g of games">
<div class="card-body">
<div class="row" *ngFor="let r of g.results">
<h5 class="card-title">{{r.title}}</h5>
<p class="card-text">{{r.game_id}}</p>
</div>
</div>
</div>
<div *ngFor="let r of games[0].results">
<div class="card-body">
<h5 class="card-title">{{r.title}}</h5>
<p class="card-text">{{r.game_id}}</p>
</div>
</div>
<div *ngFor="let g of games?.result">
<!-- Since the result part should be in a
loop -->
<div class="card-body">
<h5 class="card-title">{{g?.title}}</h5>
<p class="card-text">{{g?.game_id}}</p>
</div>
</div>