2017-06-08 31 views
0

我有一個頁面,顯示帖子列表,然後點擊每個帖子,我將顯示該帖子的評論。這工作正常,我想添加的是顯示一條消息,如果沒有評論被點擊的帖子。我試圖與建立模板這樣的:Angular 4 - 在異步調用後顯示消息

<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陣列,和一個空currentPost對象與屬性comments

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後檢查並顯示一條消息?

+0

你能嘗試重現該問題在plunker。我嘗試過並且無法複製(使用Dani建議的安全導航操作符)。 – Alex

回答

1

嘗試類似currentPost.comments?.length以擺脫該錯誤。

+0

我已經嘗試過了,但後來我也遇到了每個帖子都有#message的問題,即使是那些有意見的問題 – Leff

+0

作爲您的第二個解決方案ngIfElse - 嘗試使用'* ngIf =「currentPost.comments? .length == 0「'爲了發佈」對...沒有評論「 –

+0

我認爲問題在於它在異步調用完成之前進行評估,然後它將始終是假的 – Leff

0

解決此問題的更好方法是使用async pipe(更多信息here)。 將管道添加到* ngFor語句中。 現狀: <li *ngFor="let post of posts" (click)="select(post)">

隨着異步管: <li *ngFor="let post of posts | async" (click)="select(post)">