Async child nodes and Firebase
Hi All,
I have successfully implemented an async tree using a static structure and rxjs to simulate a backend delayed response (Observable.of(static array)). However, now that I have switched over to Firebase, I can't get any child nodes to load. Curiously, there are no errors being thrown; I just get the "loading..." element below the root node. I have tried stepping through the code, but I have no idea what's going on unless I spend a lot more time digging into it---something I don't mind doing, but would rather not if someone has already figured this stuff out.
The relevant bits of code: In my ForumTopicBrowser component:
constructor(private forumService: ForumService) {
this.options = {
getChildren: (node: TreeNode) => {
return this.forumService.getSubforums(node.data.id).toPromise();
}
}
}
And in my ForumService:
getSubforums(parentForumId: string): Observable<Forum[]> {
if (!parentForumId) {
parentForumId = '';
}
return this.afs.collection<Forum>('forums', ref => ref.where('parent', '==', parentForumId) )
.valueChanges()
.do( results => {
//Logging results just to show how many times this method is called
console.log(results);
});
}
Note that each object in the collection has a "parent" property with the unique ID of the parent node, so finding the subnodes is a simple where query (all nodes are independent objects at the first level of the forums collection). I can see through my .do operation that the correct child nodes are being returned, but they somehow get lost between the observable response and the node display (in the promise?).
I don't think this is related, but I'll mention it just in case: the getChildren function is called twice when I open the root node. I don't know if this is by design, but if it is just a random bug, then it is costing us firebase users twice as much money to load nodes asynchronously.
Thanks for any solutions, feedback, clues, or guesses you can provide. -Ashley
Solved the problem! Leaving here just in case anyone else runs into the same "issue." Not exactly sure why, but simply adding .first to firebase's return Observable did the trick:
constructor(private forumService: ForumService) {
this.options = {
getChildren: (node: TreeNode) => {
//Notice the call to .first() right here -------------v
return this.forumService.getSubforums(node.data.id).first().toPromise();
}
}
}
Still having an issue with getChildren being called once for each level of the tree when opening a node, but that is an unrelated issue...I think. Hope this helps someone. Cheers, Ashley