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

查看:68
本文介绍了带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",则在运行方法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.

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

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