【问题标题】:How to read and update the same document using angularfire2?如何使用 angularfire2 读取和更新同一个文档?
【发布时间】:2023-03-22 12:40:01
【问题描述】:

我正在使用angularfire2 尝试更新我的 Firestore 文档。我有一个参考,我使用 valueChanges 然后订阅以获取数据,但是由于我正在更新函数内部的数据,因此由于值发生变化,它将继续调用它。我想出了一个使用first()from rxjs/operators 的“黑客”解决方案,但是,必须有更好的方法来做到这一点。下面是我试图实现的代码。

this.storeCollectionRef = this.afs.collection('storeInfo');
this.storeDocumentRef= this.storeCollectionRef.doc<StoreInfo>(window.localStorage.getItem("uid"));
this.storeDocumentRef.valueChanges().subscribe(data=>{
  console.log(data.itemcount);
  var pictures = storage().ref(`${userid}/${data.itemcount+1}`);
  pictures.putString(image, "data_url").then(()=>{
    pictures.getDownloadURL().then(url => {
      this.storeInfo.itemcount = data.itemcount+1;
      this.storeInfo.image = url;
      this.storeDocumentRef.update(this.storeInfo);
    })
  });

【问题讨论】:

    标签: javascript firebase ionic3 google-cloud-firestore angularfire2


    【解决方案1】:

    令人讨厌的是,它不包含在用于处理 Firestore 文档的 official AngularFire2 docs 中。但是,您可能知道,AngularFire2 只是原始 Firebase 包的包装器 - 旨在使在 Angular 环境中使用 Firebase 变得更加容易。查看docs for the original Firebase package 提供了如何使用基本 Firebase 包实现此目标的示例:

    var docRef = db.collection("cities").doc("SF");
    
    docRef.get().then(function(doc) {
        if (doc.exists) {
            console.log("Document data:", doc.data());
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
    

    ... 这很简单。如果您使用的是原始 Firebase 包,您只需获取对您的文档的引用并调用 .get()... 如果只有 AngularFire2 包含该功能!再深入一点,它似乎也包含了该方法。查看AngularFire2 Firestore documents的源代码,底部是waaayyyyyy,最后一个方法,在valueChanges()之后,是get()!所以看起来它是受支持的,只是没有记录。

    /**
       * Retrieve the document once.
       * @param options
       */
    get(options?: firestore.GetOptions) {
        return from(this.ref.get(options)).pipe(
            runInZone(this.afs.scheduler.zone)
        );
    }
    

    我无法自己测试这个,所以我不能保证它会起作用。试试看,让我知道。作为最后的手段,如果您无法让 AF2 正常运行,您可以跳过使用 AngularFire2 包来实现该特定功能,并将原始 Firebase 包导入该组件,并使用 Firebase 包的方法来引用文档。

    编辑:

    如果不清楚,我建议您尝试以下方法:

    this.storeCollectionRef = this.afs.collection('storeInfo');
    this.storeDocumentRef= this.storeCollectionRef.doc<StoreInfo>(window.localStorage.getItem("uid"));
    
    this.storeDocumentRef.get().then( data => {
        console.log(data.itemcount);
        // ... etc...
        // continue doing your picture uploading stuff here
        // ...
    });
    

    【讨论】:

    • 感谢您的回复。这已经是我尝试过的东西了。如果您尝试最终得到一个错误,即 Property 'then' does not exist on type 'Observable'
    猜你喜欢
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多