Search code examples
angularpromiseasync-awaitangular-router

Angular: how to correctly enforce a promise to complete before navigation with routerLink?


New to angular development and need some insight on how to get async/await to work.

I have a button that makes an API call and then loads the next page. I need to wait to load the next page until the API call is complete. Problem is it's not working.

HTML Button:

<button type="button" [routerLink]="['../Review']" (click)=nextPage()">Next</button>

nextPage() Function:

private async nextPage(){ 
        await this.practiceData.put_Practice(this.practice.practiceId,this.practice).toPromise();
      });
    }
  }

http functions:

put_Practice(practiceId: number, practice: Practice)
  {
    return this.httpClient.put(this.baseUrl + '/Practice/' + practiceId, practice, this.httpOptions);
  }

Solution

  • This is because the click event handler bounded by the RouterLink directive is triggered before the promise completes. You will need to refactor your code in order to trigger the navigation manually:

    <button type="button" (click)=nextPage()">Next</button>
    
    import {Router,ActivatedRoute} from '@angular/router';
    
    export class MyComponent {
       constructor(private readonly router: Router, private readonly route: ActivatedRoute){}
    
       async nextPage(){
          await this.practiceData.put_Practice(this.practice.practiceId,this.practice).toPromise();
          await this.router.navigate(["../Review"],{relativeTo: this.route});
          // or without async/await you can simply chain the promises
       }
    }