首页 > 解决方案 > 角度参考模型并显示数据

问题描述

我添加了两个模型。这些模型相互引用,我想从评论中获取数据。当我使用以下 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>

期待你的回复。

标签: angular

解决方案


在类 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>

希望这会有所帮助


推荐阅读