网站搜索

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


我正在构建一个 Angular2 应用程序,该应用程序使用 Firebase 来存储数据,当我的应用程序加载时,我会检索所有项目并循环遍历它们,然后构建一个 HTML 表格。我从 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 表格 中的任意一行时,我希望将该错误的 UniqueId 传递给 Firebase,然后检索该记录的数据。

我有以下数据库引用:

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

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

getBug(bugId: string) {

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

    console.log(bug);

}

当这被记录到控制台时,看起来如下:

当然,这不是我预期的,我正在努力搞清楚返回与UniqueId匹配的记录的语法,我已经查阅了Firebase文档,但不幸的是,我可能搞混了,这导致我提出了这个问题。那么问题是,我如何检索与UniqueId关联的数据?

提前谢谢你。

答案#1

问题在于 child 并不返回数据;它返回的是子引用。

要访问数据,您可以使用 once 方法(它返回一个 Promise)和 value 事件。

getBug(bugId: string): Promise<Bug> {

    return this.bugsDbRef
        .child(bugId)
        .once('value')
        .then(snapshot => snapshot.val() as Bug);
}

这假设 Bug 是一个 接口。如果它是一个 类,你将需要创建一个实例:

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

而且,在这里也是,如果 Bug 是一个 class,你需要创建一个实例;只有当 Bug 是一个 interface 时,类型转换才是合适的。