Home > OS >  Stop executing code until my async/await HttpClient get operation finishes executing code (including
Stop executing code until my async/await HttpClient get operation finishes executing code (including

Time:08-04

I need to execute HttpClient get request synchronously so I found a solution on internet to use toPromise instead of subscribe and then await. However I have noticed that the this.form = = this.formBuilder.group line of code executes before myAccount is initialized by the async call. In other words I was expecting that the execution code will block until this.myAccount is initialized and then starts executing this.form = this.formBuilder.group line. Am I understanding async/await in javascript correct. What do I need to do to achieve what I want - that is, wait with execution until this.myAccount is initialized by the call await this.accountService.getById(this.id).toPromise().

ngOnInit(): void {
    this.getByIdSynchronously();

    this.form = this.formBuilder.group({
      scheduledDate: ['', Validators.required],
      required: [''],
      userAvailability: [''],
    });
}
async getByIdSynchronously()
  {
    this.myAccount = await this.accountService.getById(this.id).toPromise();
  }

I also have an html page with the first line of code looking like this:

<form [formGroup]="form" (ngSubmit)="onSubmit()" *ngIf="!isAdmin">
...
</form >

where isAdmin is a local function:

get isAdmin()
  {
    if(this.myAccount)
    {
      return this.myAccount.role == Role.Admin;
    }
    else{
      return true;
    }
  }

which executes dozen of time before my async/await method finishes so I have to return some artificial true value until my this.myAccount is initialized.

Note

I have found solution to the first problem - just use then operator of the Promise. I can't find the solution for the second problem - to stop isAdmin being called from template html until this.myAccount is initialized. Is there a remedy for that?

CodePudding user response:

Instead of Promises you should use Observables as Angular also encourages the use of Observables. The HTTPClient returns an observable so you can subscribe to it instead.

AccountService

    getById(id: number): Observable<any> {
        return this.httpClient.get(`URL goes here. ID goes into PARAMS`);
    }

Then in your component subscribe to your API call. You can use another variable to stop isAdmin from being called continuously.

isLoaded: boolean = false;
ngOnInit(): void {
      this.accountService.getById(this.id).subscribe(resp=>{
          this.form = this.formBuilder.group({
          scheduledDate: ['', Validators.required],
          required: [''],
          userAvailability: [''] });
          this.isLoaded = true;
      });
}
<form [formGroup]="form" (ngSubmit)="onSubmit()" *ngIf="isLoaded && !isAdmin">
...
</form>
  • Related