首页 文章

根据传入的UniqueId检索记录 - firebase

提问于
浏览
2

我正在构建一个使用 Firebase 存储数据的 Angular2 应用程序,当我的应用程序加载时,我检索所有项目并循环遍历它们并构建一个 HTMl table 我的代码,用于从 Firebase 检索所有错误,如下所示:

getAddedBugs(): Observable<any> {
    return Observable.create(obs => {
        this.bugsDbRef.on('child_added', bug => {
            const newBug = bug.val() as Bug;
            newBug.id = bug.key;
            obs.next(newBug);
        },
            err => {
                obs.throw(err)
            });
    });
}

结果我回来了,我转向我创建的 Bug 模型,这是按预期工作的

我想要做的是当用户点击我的 HTML table 中的任何给定行时,然后我想将该给定错误的 UniqueId 传递给 Firebase 并检索该给定记录的数据 .

我有以下db ref:

private bugsDbRef = this.fire.database.ref('/bugs');

我传入 UniqueId ,我当前的代码如下所示:

getBug(bugId: string) {

    const bug = this.bugsDbRef.child(bugId);

    console.log(bug);

}

将其记录到控制台时,它看起来如下所示:

enter image description here

当然这不是我的预期,我正在努力弄清楚返回与 UniqueId 匹配的记录的语法,我已经通过了 Firebase 文档,但不幸的是我可能会感到困惑,导致这个问题被问到 . 那么问题是如何检索链接到 UniqueId 的数据?

提前致谢 .

1 回答

  • 1

    问题是 child 没有返回数据;它返回子ref .

    要访问数据,可以使用 once 方法(返回promise)和 value 事件 .

    getBug(bugId: string): Promise<Bug> {
    
        return this.bugsDbRef
            .child(bugId)
            .once('value')
            .then(snapshot => snapshot.val() as Bug);
    }
    

    这假设 Buginterface . 如果是 class ,则需要创建一个实例:

    getBug(bugId: string): Promise<Bug> {
    
        return this.bugsDbRef
            .child(bugId)
            .once('value')
            .then(snapshot => snapshot.val() ? new Bug(snapshot.val()) : null);
    }
    

    此外,您的 Observable.create 应该返回一个删除 child_added 侦听器的函数,以便在取消订阅时清除它:

    getAddedBugs(): Observable<any> {
        return Observable.create(obs => {
            const listener = this.bugsDbRef.on('child_added',
                bug => {
                    const newBug = bug.val() as Bug;
                    newBug.id = bug.key;
                    obs.next(newBug);
                },
                err => {
                    obs.throw(err)
                }
            );
            return () => this.bugsDbRef.off('child_added', listener);
        });
    }
    

    而且,在这里,如果 Bugclass ,则需要创建一个实例;如果 Buginterface ,则仅适合演员表 .

相关问题