Can't show my array data in my page from database in angular 5?

眉间皱痕 提交于 2019-12-11 05:07:36

问题


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"  

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()
    }

}

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

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.


回答1:


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.

Try the following:

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


来源:https://stackoverflow.com/questions/48827403/cant-show-my-array-data-in-my-page-from-database-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!