Angular 4 - 异步调用后显示消息
2017-06-08
482
我有一个页面,其中显示帖子列表,单击每个帖子即可显示该帖子的评论。这很好,我想添加的是,如果单击的帖子没有评论,则显示一条消息。我曾尝试像这样设置模板:
<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>
并且在组件中,我尝试首先设置空的
posts
数组和带有属性
comments
的空的
currentPost
对象:
posts: any[] = [];
currentPost: any = {};
currentPost.comments;
然后在方法
select
中,我像这样获取评论:
this.postService.getComments(post.id)
.subscribe(
comments => this.currentPost.comments = comments,
);
但是,如果我这样做,我会收到错误:
posts.component.html:7 ERROR TypeError: Cannot read property 'length' of undefined
如何避免该错误,并在异步调用服务方法
getComments
后检查并显示消息?
2个回答
尝试使用
currentPost.comments?.length
之类的方法来消除该错误。
Dani Grosu
2017-06-08
此问题的更好解决方案是使用
async 管道
(更多信息请参见
此处
)。
将管道添加到 *ngFor 语句中。
当前情况:
<li *ngFor="let post of posts" (click)="select(post)">
使用异步管道:
<li *ngFor="let post of posts | async" (click)="select(post)">
Stefan
2017-06-08