Reputation:
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.
Upvotes: 0
Views: 286
Reputation: 8306
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>
Upvotes: 1