Angular不会将正确的数据发送到Firebase

时间:2020-04-06 17:17:33

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

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读取当前用户信息,当我在代码的其他部分尝试使用此方法时,该方法显然可行,但是我想用一些< em> text:string ,但是当我运行它时,它会在写入新信息 this.currentInfo 的同时读取数据库。因此,firebase不会使用当前信息进行更新。

作为一个例子,假设我在运行方法 sendInfo()之后,当前拥有的是currentInfo = [“ a”,“ b”,“ c”]和文本=“ d” ,只有[“ d”]是用firebase写的。

预先感谢您的帮助!

2 个答案:

答案 0 :(得分: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
      })...
    })
}

答案 1 :(得分:0)

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的另一个副本,并为循环使用一个副本,为最终值使用另一个副本。