Issue
I'm facing a problem in my project, I'm using Nested Children Routing to show data in my project, I want the data of this specific item to be shown once I click the button on it, I did the routing right, it's just I can't get the proper function for the items.
Here's my service
PostsService.service.ts
getPostById(id: string){
let docId = this.afs.collection('posts').doc(id).get()
.subscribe( doc => {
if(doc.exists){
console.log('Document Id => ', doc.id)
console.log('Document data => ', doc.data())
}else {
console.log('Document not found')
}
});
return docId;
}
and Here's my TS function for the single item
.component.ts
posts: Posts[] = [];
post!:any;
constructor(
private PostsService: PostsService,
private route: ActivatedRoute
) {}
ngOnInit(): void {
let id = this.route.snapshot.params['id']
this.PostsService.getPostById(id);
}
Solution
You're attempting the get the whole collection with getPostById() and then trying to find a single document from the results. Getting the whole colletion means you will read n amount of times for n amount of documents - which is wasteful and slow.
If you ask something with getPostById() then you should do something with the return as well. Right now your asking, but not doing anything with the return.
How about we just get the single document? It will return an Observable, so we can keep monitoring the document, or just use the face value as it is.
getPostById(id: string) {
const itemDoc = this.afs.doc<any>('posts/' + id);
return itemDoc.valueChanges();
}
And in your component, don't forget to unsubscribe from the Observable.
ngOnInit() {
let id = this.route.snapshot.params['id'];
this.PostsService.getPostById(id).subscribe(post => {
console.log(post);
})
}
Answered By - Joosep Parts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.