Leff
Leff

Reputation: 1360

Angular 4 - displaying message after an asynchronous call

I have a page where I display a list of posts, and clicking on each of them I am displaying comments for that post. That works fine, what I wanted to add is to display a message if there are no comments for the post that was clicked. I have tried with setting up the template like this:

<li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.title }}
      <ul *ngIf="currentPost == post && commentsVisible">
        <ng-container *ngIf="currentPost.comments.length > 0;else message">
          <li *ngFor="let comment of currentPost.comments" class="document">
            <p>{{ comment.author }}</p>
            <p>{{ comment.text }}</p>
          </li>
        </ng-container>
        <ng-template #message>No comments for {{ post.title }}</ng-template>
      </ul>
  </li>

And in the component, I have tried to first set the empty posts array, and an empty currentPost object with a property comments:

  posts: any[] = [];
  currentPost: any = {};
  currentPost.comments;

And then in the method select I am fetching the comments like this:

this.postService.getComments(post.id)
      .subscribe(
        comments => this.currentPost.comments = comments,
      );

But, if I do so, I get an error:

posts.component.html:7 ERROR TypeError: Cannot read property 'length' of undefined

How can I avoid that error, and check and display a message after a async call to the service method getComments?

Upvotes: 0

Views: 489

Answers (2)

Stefan
Stefan

Reputation: 321

A better solution for this problem is to use the async pipe (more info here). Add the pipe into the *ngFor statement. Current situation: <li *ngFor="let post of posts" (click)="select(post)">

With async pipe: <li *ngFor="let post of posts | async" (click)="select(post)">

Upvotes: 0

Dani Grosu
Dani Grosu

Reputation: 554

Try something like currentPost.comments?.length in order to get rid of that error.

Upvotes: 1

Related Questions