无法在角度5的数据库中显示我的页面中的数组数据?

时间:2018-02-16 13:02:41

标签: javascript angular firebase firebase-realtime-database angular5

我希望你一切都很好,所以我有一点问题,我从firebase获取数据,我有一个包含数组的数组,我想在我的视图中显示它,但我不能,我会写下我的代码,然后解释我想要实现的目标。

这是我数据库中的数据:

posts 
     --- 1 
          --- puslisher -- "Erick" 
          --- content :   "Something is written here"
          --- comments 
                      --- 1
                           --- comment : "Yes"
                           --- commentator : "Patrick"  
                      --- 2 
                           --- comment : "I dont think so "
                           --- commentator : "Sarah"
     --- 2 
          --- puslisher -- "Patrick" 
          --- content :   "News here .."
          --- comments 
                      --- 1
                           --- comment : "Yes"
                           --- commentator : "Ines"  

我在app.component.ts中获取数据:

export class AppComponent implements OnInit {

    pubs:Observable<any[]>;
    constructor(private db:AngularFireDatabase){
    }
    ngOnInit(){
       this.pubs = this.getData('/posts');
    }

    getData(path):Observable<any[]>{
       return this.db.list(path).valueChanges()
    }

}

这是我的HTML代码:

<div *nfFor="let post of pubs | async ">
    <p>publisher {{post.publisher}}</p>
    <p>content : {{post.content}}</p>
    <div>{{post.comments}}</div>
    <ul> 
       <li *ngFor="let cmt of post.comments" >{{cmt.comment}}</li>
    </ul>
</div>

但是我的控制台出错:

ERROR TypeError: Cannot read property 'comment' of undefined

但是当我只写{{cmt}}而不是{{cmt.comment}}时,我会得到这样的结果:

publisher: Erick
content : Something is written here 

,[object Object],[object Object]

- 
- [object Object]
- [object Object]



publisher: Patrick
content : News here 

,[object Object]

- 
- [object Object]

这意味着我正在获取我的对象,但第一个总是空的,我不知道为什么,我想显示我的评论文本。

我希望我能很好地解释我的问题,任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

听起来您只需要safe navigation operator,因此模板在定义之前不会尝试访问对象的属性。

尝试以下方法:

<li *ngFor="let cmt of post.comments" >{{ cmt?.comment }}</li>
相关问题