【问题标题】:Get document objects from firebase collection从 firebase 集合中获取文档对象
【发布时间】:2020-07-18 13:19:54
【问题描述】:

刚开始使用 Firebase 云,我被困住了。我希望解决方案很简单,但到目前为止我无法解决。

我使用模型创建了一个项目 (https://github.com/DragosB88/vending-machine),但现在我想使用 firebase。所以我在firebase cloud上创建了一个项目,并在那里创建了一个集合和一个对象文档:

// SET FIRESTORE PRODUCTS - function inside service
setDBProducts(data) {
       this.firestore
           .collection('vendingProducts') // collection name on Cloud Firestore
           .doc('products')               // document name on Cloud Firestore
           .set(Object.assign({}, data)); // it only accepts objects, thus arrays must be converted
    }

效果很好:

firebase data

问题在于,当我尝试检索数据时,我得到了不同的对象(取决于我提出的请求),这些对象不包含 firebase 上的任何数据。

  // GET FIRESTORE PRODUCTS - service function
  getDBProducts() {
    return this.firestore.collection('vendingProducts').doc('products').get();
  }
  
  // ---------------------------------------------------------------
  // GET FIRESTORE PRODUCTS - component function inside constructor

 this.dbProducts = ProductsService.getDBProducts().subscribe(
    (res) => (this.dbProducts = res)
 );
 // this.dbProducts = ProductsService.getDBProducts();
 console.log('DATABASE PRODUCTS: ', this.dbProducts);

this is what I receive upon subscribing

如何从 firebase 获取产品? (顺便说一句,我也是 observables 的新手)

【问题讨论】:

    标签: angular firebase google-cloud-firestore crud


    【解决方案1】:

    数据是从 Firebase 异步加载的。任何需要访问数据的代码都需要在您的 subscribe 回调中(或从那里调用)。

    在您当前的代码中,当您的 console.log('DATABASE PRODUCTS: ', this.dbProducts) 运行时,this.dbProducts = res 尚未执行。

    所以这是一种解决方案:

     this.dbProducts = ProductsService.getDBProducts().subscribe((res) => {
        this.dbProducts = res;
        console.log('DATABASE PRODUCTS: ', this.dbProducts);
     });
    

    【讨论】:

    • 是的,谢谢,这是我的失误。但是我仍然没有检索产品,而是检索以下对象:ibb.co/25Sn3Nn 如果我在控制台中过滤了 firebase 数据库中的任何产品,我看不到任何产品。
    猜你喜欢
    • 2020-01-09
    • 2020-04-23
    • 2020-07-15
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2018-12-15
    相关资源
    最近更新 更多