【问题标题】:How to get single item from firebase realtime database?如何从firebase实时数据库中获取单个项目?
【发布时间】:2020-12-01 04:01:43
【问题描述】:

我有一个组件和一个服务,它们旨在协同工作以从我的 firebase 实时数据库中检索项目。

实时数据库存储人员及其名字(fname)和姓氏(lname)。

在我的组件中,“id”是从 URL 中检索到的,这是 firebase 中的唯一 id。
然后,我的编辑组件将服务引用到 getSingleItem(this.id)。
这是组件 ts 文件中的一部分:

constructor(
     private es: Service
){ }

ngOnInit() {
     // This code graps the "id" from the URL
     this.sub = this.route.params.subscribe(params => {
      this.id = params["id"];
    });

    this.item = this.es.getSingleItem(this.id);
    console.log(this.item); //returns strange object
    console.log(this.item.fname);// shows as undefined.
    console.log(this.item.lname);//shows as undefined
    

    this.editForm = this.fb.group({
      fname: [null], //cant get this.item.fname (comes as undefined)
      lname: [null]  //cant get this.item.fname (comes as undefined)
    });

然后在我的服务中,getSingleItem() 看起来像这样:

constructor(
private fdb: AngularFireDatabase
){ }

getSingleItem(id: string) { 
      const itemPath =  `people/${id}`;
      this.item = this.fdb.list(itemPath);
      return this.item
    }

但是回到组件中,当我 console.log(this.item) 它返回一个看起来像这样的奇怪对象: {query: Reference, update: ƒ, set: ƒ, push: ƒ, remove: ƒ, …} 没有我想看到的实际数据的痕迹。

当我尝试执行 console.log(this.item.fname)console.log(this.item.lname) 时,它是未定义的。

如何正确地从数据库中检索项目?

【问题讨论】:

    标签: angular typescript firebase firebase-realtime-database


    【解决方案1】:

    您需要订阅this.fdb.list(itemPath) 返回的侦听器。

    例如:

    this.fdb.list(itemPath).valueChanges((value) => console.log(value));
    

    或者如果您需要文档 ID 和值:

    this.fdb.list(itemPath).snapshotChanges((doc) => console.log(doc.id, doc.data()));
    

    您可能还需要使用doc 而不是list,因为您正在观察单个文档。

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      相关资源
      最近更新 更多