【问题标题】:Angular doesn't send the right data to firebaseAngular 没有向 firebase 发送正确的数据
【发布时间】:2020-04-06 17:17:33
【问题描述】:
private currentInfo:string[];
private useruid: string;
...
constructor(private AngularAuth: AngularFireAuth,
    private db:AngularFirestore) { }

...

sendInfo(text:string){
    this.readInfo();
    this.currentInfo.push(text);
    this.db.collection('users').doc(this.useruid).update({
        Info: this.currentInfo
    })
}
...
readInfo(){
    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);
      });
    })
}

下午好,我找不到这个问题的解决方案, 我有 1 个方法 readInfo( ) 从 firebase 读取当前用户信息,当我在代码的其他部分之外尝试它时,这个方法显然有效,但是我想用一些更新这个信息 text:string,但是当我运行它时,它会在写入新信息 this.currentInfo 的同时读取数据库。因此,firebase 不会使用当前信息进行更新。

作为一个例子,假设我当前有 as currentInfo = ["a","b","c"] 和 as text = "d",在运行方法 sendInfo( ) , 只有 ["d"] 是用 firebase 写的。

提前感谢您的帮助!!

【问题讨论】:

    标签: javascript firebase ionic-framework google-cloud-firestore angularfire2


    【解决方案1】:

    这里的snapshotChanges() 方法是异步的,因此在读取结束之前完成了写入。然后将您的 update 语句移动到 subscribe 调用中:

    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);
          });
          // Add the text to currentInfo and save
          this.currentInfo.push(text);
          this.db.collection('users').doc(this.useruid).update({
            Info: this.currentInfo
          })...
        })
    }
    

    【讨论】:

      【解决方案2】:
      sendInfo(text:string){
      this.readInfo(); //As Olivier Depriester said this function is called but you are not waiting for the data to be read.
      this.currentInfo.push(text);
      this.db.collection('users').doc(this.useruid).update({
          Info: this.currentInfo
      })
      

      }

      对于无限循环问题,声明 this.currentInfo 的另一个副本并将一个用于循环,另一个用于最终值。

      【讨论】:

        猜你喜欢
        • 2018-07-20
        • 2017-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 2014-11-23
        • 2020-10-01
        相关资源
        最近更新 更多