Rob*_*Rob 3 firebase typescript angular google-cloud-firestore
有这两种方法。我有一个在调用this.family之前调用getFamily方法的类,因为onSnapshot尚未完成加载。我该如何重组它,以便对getFamily的调用将等待onsnapshot完成?可以使用诺言吗?
getFamily() {
return this.family;
}
setFamilyID(familyID) {
this.familyID = familyID;
this.db.collection("families").doc(this.familyID).onSnapshot((familyDoc) => {
console.log("family updated");
this.family = familyDoc;
});
}
Run Code Online (Sandbox Code Playgroud)
如果您需要实时更新,请包装 onSnapshot在Promise。您需要对返回值进行处理,onSnapshot以便在销毁组件时分离。另外,请确保只拨打resolve一次。
getFamily() {
return this.family;
}
setFamilyID(familyID) {
this.familyID = familyID;
return new Promise((resolve, reject) => {
var resolveOnce = (doc) => {
resolveOnce = () => void;
resolve(doc);
};
this.detachFamilyIDWatcher = this.db
.collection("families").doc(this.familyID)
.onSnapshot((familyDoc) => {
console.log("family updated");
this.family = familyDoc;
resolveOnce(familyDoc);
}, reject);
});
}
Run Code Online (Sandbox Code Playgroud)
如果您只需要加载一次数据,则使用get代替onSnapshot。get返回a Promise,不需要分离。
getFamily() {
return this.family;
}
setFamilyID(familyID) {
this.familyID = familyID;
return this.db
.collection("families").doc(this.familyID)
.get().then((familyDoc) => {
console.log("family updated");
this.family = familyDoc;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1706 次 |
| 最近记录: |