带有火力和角度的无限循环 [英] Infinit loop with firebase and angular

查看:24
本文介绍了带有火力和角度的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 firebase 保存我的数据时遇到了一个无限循环问题this.db.collection('users').doc(this.useruid).update({Info: this.currentInfo})

I'm having an infinit loop problem saving my data on firebase with this.db.collection('users').doc(this.useruid).update({Info: this.currentInfo})

private currentInfo:string[];
private useruid: string;
...
constructor(private AngularAuth: AngularFireAuth,
    private db:AngularFirestore) { }

...

sendInfo(text:string){
    this.useruid = this.AngularAuth.auth.currentUser.uid;
    this.db.collection('users').doc(this.useruid).snapshotChanges().subscribe(a=>{
      const data = a.payload.data() as {name:string, Info:string[]};
      data.Info.forEach(element => {
        this.currentInfo.push(element);
      });
      this.currentInfo.push(text);
      this.db.collection('users').doc(this.useruid).update({
        Info: this.currentInfo
      })...
    })
}

举个例子,假设我目前有 currentInfo = ["a","b","c"]text = "d",在y 运行方法 sendInfo( ),我得到一个循环:["a","b","c","d","a","b","c","d","d","a","b","c","d","a","b","c","d","d","d"...] 等等.

As an example, imagine I currently have as currentInfo = ["a","b","c"] and as text = "d", after y run the method sendInfo( ), i get a loop with: ["a","b","c","d","a","b","c","d","d","a","b","c","d","a","b","c","d","d","d"...] and so on.

推荐答案

要根据当前值更新文档,使用交易:

To update a document based on its current value, use a transaction:

var userDocRef = collection('users').doc(this.useruid);

return db.runTransaction(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(userDocRef).then(function(userDoc) {
        if (!userDoc.exists) {
            throw "Document does not exist!";
        }

        const data = userDoc.data() as {name:string, Info:string[]};
        data.Info.forEach(element => {
          this.currentInfo.push(element);
        });
        this.currentInfo.push(text);

        transaction.update(userDocRef, { Info: this.currentInfo });
    });
}).then(function() {
    console.log("Transaction successfully committed!");
}).catch(function(error) {
    console.log("Transaction failed: ", error);
});

除了防止您当前拥有的无限循环之外,这还可以防止多个用户几乎同时更新文档时覆盖彼此的结果.

In addition to preventing the infinite loop that you currently have, this also prevents multiple users from overwriting each other's results if they want to update the document at almost the same time.

这篇关于带有火力和角度的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆