javascriptangularangularjs-scope

Angular: Call method after DOM update


I am calling a method(which calls a rest service) from html to increment/decrement a count on the screen. Now I want to call another method (i.e. getThreshold) to check if the count reaches a threshold value. If yes I want to show a confirmation message.

I want to update the count on the screen first then call the function to check if it reaches the threshold. But now it is calling the function and rest call first, then updating the count on the screen.

I have to show a confirm dialog before I call the next rest call. But the dialog is showing up before updating the count on the screen.

So here is my code:

component.html

<table>
  <tr>
    <td><a [routerLink]="" (click)="updateCount(inspect, 'A', 'M')" class="btn btn-success">A-</a></td>
  </tr>
  </table

component.ts

updateCount(inspection, rankName: string, rankPlusOrMinus: string) {
  inspection.rankName = rankName;
  inspection.rankPlusOrMinus = rankPlusOrMinus;
  const url = '/api/xyz';
  this.http
    .post(url, JSON.stringify(inspection), {
      headers: this.headers
    })
    .toPromise()
    .then(response => {
      let data = response.json();
      if (rankName = 'A') inspection.rankAcount = data.rankAcount;   // if I call getThreshold from here, it calls the function and rest call and displays alert message. But the count in A is NOT incremented yet
    })
    .catch(error => {}
    }

  getThreshold(rankName: string, rankAcount: number) {
    const url = '/api/threshold';
    this.http
      .get(url)
      .toPromise()
      .then(response => {
        // Some Logic
        // Show alert message
      })
      .catch(error => {});
  }
}

Solution

  • You can use flatMap for ordering APIs as:

    updateCount(inspection, rankName: string, rankPlusOrMinus: string) {
        this.sendToServer(inspection, rankName, rankPlusOrMinus).flatMap((countResult) => {
            // Here you can update your view
            inspection.rankAcount = countResult.rankAcount;
            return this.http.get('/api/threshold').subscribe(response => {
                        // Some Logic
                        // Show alert message
                                        setTimeout(() => {alert('hi');});
                   });
                }
            }
        );
    }
    
    sendToServer(inspection, rankName, rankPlusOrMinus) {
        inspection.rankName = rankName;
        inspection.rankPlusOrMinus = rankPlusOrMinus;
        const url = '/api/xyz';
        this.http.post(url, JSON.stringify(inspection), {headers: this.headers}).map((res: Response) => res.json());
    }
    

    Solution 2

    add timeout after first API's response:

    ...
    if (rankName = 'A') inspection.rankAcount = data.rankAcount;
    setTimeout(() => {
        this.getThreshold(rankName, rankAcount);
    });
    ...