我正在尝试在创建文档ID时返回它。由于Firebase函数是异步的,因此返回值直到查询完成才完成。如何防止这种情况,以便在查询完成后可以等待获取值?
此功能创建的文档位于服务中:
public makeDoc(title: string, score: number): any{
const fields = {
title: title,
score: number
}
this.db.collection('saved').add(fields)
.then(function(ref) {
console.log(ref.id);
return ref.id;
})
}
我通过位于组件中的函数来调用它:
onCreate() {
const str = this.createService.makeDoc(this.title, this.score);
console.log(str);
}
答案 0 :(得分:0)
尝试以下操作:
const fields = {
title: title,
score: number
}
var newFieldsRef = this.db.collection('saved').push();
this.db.collection('saved').child(newFieldsRef).set(fields);
var id = newFieldsRef.toString();
答案 1 :(得分:0)
您不想阻止等待查询完成,您应该在此处使用Promise。
首先,如果没有,请确保将 @Override
public void onInfoWindowClick(Marker marker) {
if(customInfoWindowAdapter.getInfoContents(marker).findViewById(R.id.chat).getTag().equals("chatTag")) {
// any code here
}
}
命名空间导入服务:
firestore
现在,为您服务:
由于没有以有效的方式创建import { firestore } from 'firebase';
对象(例如,重用makeDoc
类型),我不得不稍微更改您的fields
方法:
number
这现在返回一个public makeDoc(titleParam: string, scoreParam: number): Promise<firestore.DocumentReference> {
const fields = {
title: titleParam,
score: scoreParam
};
return this.db.collection('saved').add(fields);
}
,当解析后,引用将指向创建的文档。
现在,在onCreate中对其的调用如下:
Promise<DocumentReference>
这将在ID可用时立即记录。