【问题标题】:How do i retrieve data with its key firebase如何使用其关键火力库检索数据
【发布时间】:2017-11-05 09:38:05
【问题描述】:

假设我们有一个数据库:

Recipes
   recipe_key(some uniq key generated when data pushed)
          ingredients:pepper

如何使用 recipe_key 检索辣椒值?我检查了 angularfire2 的文档,它说使用快照更改,但是使用此代码我只能获得“食谱”。我想我需要再往下一层?

    constructor(afDb: AngularFireDatabase) {
      afDb.object('/recipes/').snapshotChanges().map(action => {
        const $key = action.payload.key;
        const data = { $key, ...action.payload.val() };
        return data;
      }).subscribe(item => console.log(item.$key));
    }

【问题讨论】:

  • 什么是'items/1'?
  • 哦,对不起,我直接从文档中获取了该代码,它应该是食谱

标签: firebase firebase-realtime-database angularfire2


【解决方案1】:

文档是正确的,您应该使用快照更改,以便您可以从有效负载对象中获取 key 属性。

看你的代码我相信你忘了给AngularFireDatabaseobject()方法添加key

const recipeKey = '<your-push-key>';
afDb.object(`/recipes/${recipeKey}`).snapshotChanges().map(action => {
    const $key = action.payload.key;
    const data = { $key, ...action.payload.val() };
    return data;
}).subscribe(item => console.log(item.$key));

如果你想检索一个带有 $key 属性的列表,你可以使用这个方法。

afDb.list(`/recipes`).snapshotChanges().map(actions => {
    return actions.map(action => {
        const $key = action.payload.key;
        const data = { $key, ...action.payload.val() };
        return data;
    });
}).subscribe(items => console.log(items));

【讨论】:

  • 如果我不知道 recipeKey 怎么办
  • 我没有定义
  • .subscribe 调用包含该列表中的所有项目。我再次更新了我的答案,现在应该可以了。
猜你喜欢
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多