angular - 角度参考模型并显示数据
问题描述
我添加了两个模型。这些模型相互引用,我想从评论中获取数据。当我使用以下 html 代码时,一切都很好,但代码不起作用:@{{comment.user?.name}}。请查看以下代码,如果您有任何指导方针,请告诉我?谢谢
**These two Models i am using in the source code: User and Comment**
import { Video } from './Videos';
export class User{
constructor(
public id?:number,
public name?:string,
public type?: string,
public video?: Video,
public comment?: Comment){}
}
import { User } from './user';
import { Video } from './Videos';
export class Comment{
constructor(
id:number,
userId: number,
videoId:number,
date:Date,
body:string,
user?:User[],
video?:Video[] ){ }
}
**It is a component Ts source code :**
export class CommentslistComponent implements OnInit {
public comments:Comment[]=[];
constructor(private videoService:VideoService) { }
ngOnInit() {
this.videoService.getComments()
.then((response) => {response.json()
.then((res:Comment[])=>{
this.comments=res;
console.log(res);
});
})
}
**HTML file where i want to display the data**
<li class="media" *ngFor="let comment of comments">
<a href="#" class="pull-left">
<img src="https://bootdey.com/img/Content/user_1.jpg" alt="" class="img-circle">
</a>
<div class="media-body">
<span class="text-muted pull-right">
<small class="text-muted">{{comment.date}}</small>
</span>
<strong class="text-success" > @{{comment.user?.name}}</strong>
<p>
{{comment.body}}
</p>
</div>
</li>
期待你的回复。
解决方案
在类 Comment 你有 user?:User[] 这是用户类型的数组。这就是为什么{{comment.user?.name}}
不工作的原因。它将像{{comment.user[0]?.name}}
. 希望你能明白我的意思。因此,在 HTML 中,您可以使用 *ngFor 来表示 comment.user,如下所示:
<li class="media" *ngFor="let comment of comments">
<a href="#" class="pull-left">
<img src="https://bootdey.com/img/Content/user_1.jpg" alt="" class="img-circle">
</a>
<div class="media-body">
<span class="text-muted pull-right">
<small class="text-muted">{{comment.date}}</small>
</span>
<strong class="text-success" *ngFor="let item of comments.user">
{{item?.name}}
</strong>
<p>
{{comment.body}}
</p>
</div>
</li>
希望这会有所帮助
推荐阅读
- spring - @RequestBody 在 Spring Boot 中不起作用
- python - Python 中的异常处理,无需大量的异常语句
- salesforce - 如何使用用户名和密码验证用户?
- reactjs - 我可以实时访问我的 heroku 应用程序,但我的朋友只能看到白色的空白页?
- windows-installer - 启用 MSI 安装程序的安装日志,无需任何命令行参数
- amazon-web-services - AWS ECS 上的 NTP 时间同步服务
- css - 使 HTML Unicode (UTF-8) 参考图标变细
- c# - 模型验证多语言翻译在 .net 核心中不起作用
- java - Java Swing - 在多个面板或单个面板中更有效地绘制
- c++ - 如何在qt中绘制一个带彩色角的透明矩形?