要求的行为:
我想创建一个 AngularService,它检查某个文档是否存在并根据结果更新全局变量。
当前状态
该函数成功检查文档是否存在。它还会更新 if/else 语句中的全局变量。
问题
甚至,第一部分运行良好,它总是返回“未定义”。
我该如何解决?与功能范围有关吗?
我的服务:
export class ProfileFollowService {
//global variable which should be updated
followState: boolean;
constructor(private angularFirestore: AngularFirestore) { }
checksFollow(followingID: string, followerID: string): boolean {
const followDoc =
this.angularFirestore.collection(`users/${followingID}/following`).doc(followerID).ref;
followDoc.get().then((doc) => {
if (doc.exists) {
this.followState = true;
} else {
this.followState = false;
}
});
return this.followState;
}
}
最佳答案
followDoc.get() 是返回 promise 的异步函数。为了返回更新的 this.followState 你必须等待 then
一种方法是使用 async/await
async checksFollow(followingID: string, followerID: string): boolean {
const followDoc =
this.angularFirestore.collection(`users/${followingID}/following`).doc(followerID).ref;
return followDoc.get().then((doc) => {
if (doc.exists) {
this.followState = true;
} else {
this.followState = false;
}
return this.followState;
});
}
在您调用 checksFollow
的代码的其他部分您可以输入关键字 await
并等待响应。
async someMethodToCallChecksFollow() {
const result = await this.checksFollow();
console.log(result);
}
如果你想在你的 html 中使用响应,我建议将 followState 从原始 boolean
更改为至 BehaviorSubject<boolean>
然后调用this.followState.next(true)
例如:
export class YourService {
public followState = new BehaviorSubject<boolean>(false);
async checksFollow(followingID: string, followerID: string): boolean {
const followDoc =
this.angularFirestore.collection(`users/${followingID}/following`).doc(followerID).ref;
return followDoc.get().then((doc) => {
if (doc.exists) {
this.followState.next(true);
} else {
this.followState.next(false);
}
return this.followState.getValue();
});
}
}
然后在您的 html 中您可以使用 async
管道。
<div *ngIf="yourServiceInstance.followState | async">It is true</div>
关于javascript - Angular Firestore : Check if data exist and update a global variable based on that,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55007304/