要求的行为:
根据 Angular 服务返回的 bool 值在 Angular View 中显示按钮,该服务检查 Firestore 文档是否存在
当前状态
服务成功检查文档是否存在。它还更新 if/else 语句中的全局变量。我可以调用服务中的函数,它会记录 bool 值,但不会返回它。
问题
当我从组件调用该函数时,它总是记录 [object Promise]
我收到 ts lint 错误:Type 'Promise<Boolean>' is not assignable to type 'boolean'.
我该如何解决这个问题?我是否必须将 Promise 转换为 bool 值或 Observable?
我的服务:
export class ProfileFollowService {
// global variable which should be updated
followState: boolean;
// checks if the document exist and returns a boolean
async checkFollow(followingID: string, followerID: string): Promise<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;
});
}
async callCheckFollow(followingID: string, followerID: string) {
const result = await this.checkFollow(followingID, followerID);
console.log(result); //logs true or false as requested
return result;
}
}
我的组件类:
export class ServiceTestComponent implements OnInit {
followState: boolean;
constructor(private followService: ProfileFollowService) {
// throws TS Lint error: Type 'Promise<Boolean>' is not assignable to type 'boolean'.
this.followState = this.followService.callCheckFollow('someID', 'someID');
// logs [object Promise], should log true or false
ngOnInit() {console.log('followstate' + this.followState);}
}
我的组件 html:
<div *ngIf="followState === true">
<p>hello Doc</p>
</div>
<div *ngIf="followState === false">
<p>No doc</p>
</div>
最佳答案
在组件 typescript 中,您有一个 bool 属性,并且您将其分配给构造函数内的 Promise。
将代码移动到 ngOnInit
之前添加 async
关键字,并在分配 followState 之前使用关键字 await
export class ServiceTestComponent implements OnInit {
followState: boolean;
constructor(private followService: ProfileFollowService) { }
// logs [object Promise], should log true or false
async ngOnInit() {
console.log('followstate' + this.followState);
this.followState = await this.followService.callCheckFollow('someID', 'someID');
}
}
关于javascript - Angular Firestore 根据返回的 bool 值显示一个按钮,该 bool 值检查 Firestore 文档是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55020175/