почему мой код делает бесконечное l oop, когда я вызываю api? - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь вызвать свой api, чтобы получить имя tp, но в представлении я вижу только [object promise], а в консоли браузера похоже, что он выполняет бесконечное l oop

html:

<table [dtOptions]="dtOptions" class="row-border hover" datatable>
  <thead>
  <tr>
    <th>Date</th>
    <th>Intitulé</th>
    <th>Résultat</th>
    <th>Coefficiant</th>
  </tr>
  </thead>
  <tbody *ngIf="grades?.length != 0">
  <tr *ngFor="let grade of grades">
    <td>{{ formatDate(grade.Date) | date : 'MM/dd/yyyy hh:mm'}}</td>
    <td>{{ getTpName(grade.tp_id) }}</td>
    <td><b>{{ grade.Grade | number:'2.1-2' }}/20</b></td>
    <td>{{ grade.coeff | number:'1.1'}}</td>
  </tr>
  </tbody>
  <tbody *ngIf="grades?.length == 0">
  <tr>
    <td class="no-data-available" colspan="4">Aucune note enregistées</td>
  </tr>
  <tbody>
</table>

TS:

  async getTpName(tp_id: any) {
    return  await this.apiService.getTpName(tp_id);
  }

apiservice> getTpName

  getTpName(tp_id) {
    let url = `${this._tpUrl}/readName/${tp_id}`;
    return new Promise((resolve, reject) => {
      this.http.get(url, {headers: this.headers}).subscribe(
        res => resolve(res),
        error => reject(error)
      )
    });
  }

Знаете ли вы, почему это происходит и как это исправить?

РЕДАКТИРОВАТЬ: вот моя вкладка сети

1 Ответ

1 голос
/ 13 июля 2020

Было бы хорошо переместить вызов api из html в компонентный контроллер.

ngOnInit() {
   grades.forEach(grade => {
       this.getTpName(grade.tp_id)
           .pipe(take(1))
           .subscribe(tpName => {
                grade.tpName = tpName;
           });
   });
}
< td > {{ grade.tpName | json }}</td >
...