简体   繁体   中英

How to disable button until an async function call is over?

I have a button on the frontend that calls an async method which then calls an external REST Controller to refresh (delete current -> create new) a Calendar. The problem is that if the button is clicked multiple times before the first REST call process is completed, it creates multiple calendars. I want to disable the refresh button until the async method (and the REST call inside of it) is finished. How can this be achieved? I am using Angular4.

I tried using a flag that I set as soon as the function is called and reset it at the end of the function. This did not work.

HTML button code:

<!-- refresh button -->
<button md-button type="button" class="mat-button active (click)="refreshCalendar(team)">
  Refresh
</button>

Async refreshCalendar method:

  async refreshCalendar(teamName: string) {
    // Some code ..

    this.calendarSvc.refreshCalendarForTeam(teamId);
  }

Async refreshCalendarForTeam method:

  async refreshCalendarForTeam(teamId: number) {
    // URL creation ..

    return this.http.post(url, {}) // REST call here
      .map(response => {
        return response.toString();
      }).subscribe(() => { });
  }

Just Use a variable IsCalling:boolean=false . Your code would look like this:

IsCalling:boolean=false

callAsyncFunction()
{
    IsCalling=true;

    async refreshCalendar(teamName: string) {
        // Some code ..
        IsCalling=false;
        this.calendarSvc.refreshCalendarForTeam(teamId);
    }
}

Your HTML would be

<button [disabled]='IsCalling' md-button type="button" class="mat-button active (click)="refreshCalendar(team)">
  Refresh
</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM