Home > Software engineering >  How to get a boolean data from my API and use it
How to get a boolean data from my API and use it

Time:08-08

I can't get data from my back.

file.html

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

file.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');
 }
}

I would like this.checkData to return true. I would like to use this.checkData in the update method.

CodePudding user response:

Since this.check() is an asynchronous action and you want to do something when it's finished, you need to return the underlying Observable and subscribe to it from the other methods:

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");
    }
  });
}
  • Related