Javascript 角度不';t将正确的数据发送到firebase
下午好,我找不到这个问题的解决办法, 我有一个方法readInfo()从firebase读取当前用户信息,除了代码的其他部分外,当我尝试该方法时,该方法显然有效,但是我想用一些text:string更新此信息,但是当我运行它时,它在写入新信息this.currentInfo的同时读取数据库。因此firebase不会使用当前信息进行更新 例如,假设我当前有As currentInfo=[“a”、“b”、“c”]和As text=“d”,在y运行方法sendInfo()之后,只有[“d”]是用firebase编写的 提前感谢您的帮助 此处的Javascript 角度不';t将正确的数据发送到firebase,javascript,firebase,ionic-framework,google-cloud-firestore,angularfire2,Javascript,Firebase,Ionic Framework,Google Cloud Firestore,Angularfire2,下午好,我找不到这个问题的解决办法, 我有一个方法readInfo()从firebase读取当前用户信息,除了代码的其他部分外,当我尝试该方法时,该方法显然有效,但是我想用一些text:string更新此信息,但是当我运行它时,它在写入新信息this.currentInfo的同时读取数据库。因此firebase不会使用当前信息进行更新 例如,假设我当前有As currentInfo=[“a”、“b”、“c”]和As text=“d”,在y运行方法sendInfo()之后,只有[“d”]是用fir
snapshotChanges()
方法是异步的,因此在读取结束之前完成写入。然后将您的update
语句移动到subscribe
调用中:
sendInfo(文本:字符串){
this.useruid=this.AngularAuth.auth.currentUser.uid;
this.db.collection('users').doc(this.useruid).snapshotChanges().subscribe(a=>{
const data=a.payload.data()为{name:string,Info:string[]};
data.Info.forEach(元素=>{
此.currentInfo.push(元素);
});
//将文本添加到currentInfo并保存
此.currentInfo.push(文本);
this.db.collection('users').doc(this.useruid).update({
Info:this.currentInfo
})...
})
}
}
对于infinte循环问题,请声明this.currentInfo的另一个副本,并将其中一个用于循环,另一个用于最终值
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);
});
})
}
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
})