Angular:DOM更新后的调用方法

时间:2018-04-13 02:30:30

标签: javascript angular angularjs-scope

我从html调用一个方法(调用休息服务)来增加/减少屏幕上的计数。现在我想调用另一个方法(即getThreshold)来检查计数是否达到阈值。如果是,我想显示确认信息。

我想首先更新屏幕上的计数,然后调用该函数来检查它是否达到阈值。但现在它首先调用函数和rest函数,然后更新屏幕上的计数。

我必须在拨打下一个休息电话之前显示确认对话框。但是在更新屏幕上的计数之前,对话框正在显示。

所以这是我的代码:

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 increamented 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 => {});
  }
}

2 个答案:

答案 0 :(得分:1)

您可以使用flatMap将API排序为:

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());
}

解决方案2

在首次API响应后添加timeout

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

答案 1 :(得分:0)

如果您有权编辑API,我认为由于第一次POST而在JSON对象中返回阈值是有意义的。这样您就不必单独调用来获取阈值。您也可以返回一个布尔值,判断阈值是否被命中。

实施例:

&#13;
&#13;
this.http
  .post(url, JSON.stringify(inspection), {
    headers: this.headers
  })
  .toPromise()
  .then(response => {
    let data = response.json();
    let threshold = data.threshold;
    let result = data.inspection;
    if (rankName = 'A') {
      inspection.rankAcount = result.rankAcount;
      if (result.rankAccount == threshold) {
        //confirmation box here.
      }
    }
  })
  .catch(error => {}
  }
&#13;
&#13;
&#13;