如何从我的API获取布尔数据并使用它



我无法从背后获取数据。

file.html

<div *ngIf="shouldDisplay">
<p> information to disiplay </p>
<button mat-flat-button type="button" (click)="update()">
update
</button>
</div>

文件.ts

shouldDisplay: boolean;
ngOnInit() {
this.check();
//this.shouldDisplay return undefined
this.shouldDisplay = this.checkData;
}
check() {
this.fileService.check().subscribe( data => {
//data return true
this.checkData = data;
});
}
update(){
this.check();
//this.checkData return undefined
if(this.checkData){
this.fileService.update();
}else{
this.notificationService.error('errorMessage');
}
}

我希望this.checkData返回true。我想在更新方法中使用this.checkData。

由于this.check()是一个异步操作,并且您希望在它完成时执行某些操作,因此需要返回底层Observable并从其他方法订阅它:

ngOnInit(): void {
this.check().subscribe(() => this.shouldDisplay = this.checkData);
}
check(): Observable<boolean> {
return this.fileService.check().pipe(
tap(data) => this.checkData = data)
);
}
update(): void {
this.check().subscribe(() => {
if (this.checkData) {
this.fileService.update();
} else {
this.notificationService.error("errorMessage");
}
});
}

最新更新