【发布时间】:2019-03-06 09:56:15
【问题描述】:
要求的行为:
根据返回的 Angular 服务的布尔值在 Angular 视图中显示一个按钮,该布尔值检查 Firestore 文档是否存在
当前状态
服务成功检查文档的存在。它还会更新 if/else 语句中的全局变量。我可以在服务中调用该函数,它会记录布尔值,但不会返回它。
问题
当我从组件调用函数时,它总是记录 [object Promise] 并且我得到一个 ts lint 错误:Type 'Promise<Boolean>' is not assignable to type 'boolean'.
我该如何解决?我是否必须将 Promise 转换为布尔值或 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>
【问题讨论】:
标签: javascript angular typescript function google-cloud-firestore