Home > front end >  Angular loop through Object in array
Angular loop through Object in array

Time:04-13

Hi this is my angular project and I want to get userName of user for every posted comment. The entities are from my spring boot project. Is there a way to get a username for every comment?

This is comment log.

enter image description here

This is my comments Service class

  getAllCommentsForPost(postId: string): Observable<Comment[]>{
    return this.http.get<Comment[]>(this.PATH_OF_API   "/api/comment/get" postId)
 }

This is my component

  this.commentService.getAllCommentsForPost(this.router.url).subscribe((data: Comment[]) =>{
      this.comments = data;
    })

Html

 <div  style="width: 60%" *ngFor="let comment of comments">

    {{comment.comment}}
    <p *ngIf="comment.voteCount > 0"  style="color: green">  Likes: {{comment.voteCount}} </p>
    <p *ngIf="comment.voteCount == 0"  style="color: black"> Likes: {{comment.voteCount}} </p>
    <p *ngIf="comment.voteCount < 0"  style="color: red"> Likes: {{comment.voteCount}} </p>
    <a [routerLink]="['/like', comment.commentId]">  <p>like</p>  </a>
  </div>

I am getting error when i add

{{comment.user.userName}} 
{{comment.user['userName']}}

CodePudding user response:

What you are doing should work. I would prevent such errors with the use of ? when accessing props. It might be, that not each comment has a userName (perhaps a anonymous comment of a sort?).

{{comment?.user?.userName}} 

CodePudding user response:

I guess you are using latest version of Typescript in new version of typescript there are Optional Chaining where your object are null & undefined then this Optional Chaining operator will help you determine this object id null or undefined
and in your case Optional Chaining(?) operator will help you
Click here to known more about optional chaining

  • Related