无法在角度5的数据库中的页面中显示我的数组数据? [英] Can't show my array data in my page from database in angular 5?

查看:52
本文介绍了无法在角度5的数据库中的页面中显示我的数组数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望您一切都好,所以我遇到了一个小问题,我正在从Firebase获取数据,并且我有一个包含数组的数组,我想在我的视图中显示它,但我不能,编写我的代码,并解释我以后想要实现的目标.

I hope you're all fine, so I am having a little problem, I am getting data from firebase and I have an array containing an array and I want to show it in my view but I can't, I will write my code and explain what I want to achieve later.

这是我数据库中的数据:

This is the data in my database :

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中获取数据:

I get the data in my 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代码:

Here is my HTML code :

<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>

但是我的控制台出现错误:

But I am getting an error in my console :

ERROR TypeError: Cannot read property 'comment' of undefined

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

But when I write only {{cmt}} instead of {{cmt.comment}}, I get something like this :

publisher: Erick
content : Something is written here 

,[object Object],[object Object]

- 
- [object Object]
- [object Object]



publisher: Patrick
content : News here 

,[object Object]

- 
- [object Object]

这意味着我要拿到我的对象,但是第一个总是空的,我不知道为什么,我想显示我的注释文本.

Which means That I am getting my objects but the first one is always empty, I don't know why, and I want to show my comment text.

我希望我能很好地解释我的问题,对我们的帮助将不胜感激.

I hope I well explained my problem, any help would be much appreciated.

推荐答案

听起来您只需要安全导航操作符,因此模板在定义对象之前不会尝试访问其属性.

It sounds like you just need the safe navigation operator so the template doesn't try to access the properties of the object before it is defined.

请尝试以下操作:

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

这篇关于无法在角度5的数据库中的页面中显示我的数组数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆