【问题标题】:why my code make an infinite loop when I call the api?为什么当我调用 api 时我的代码会无限循环?
【发布时间】:2020-11-02 13:25:27
【问题描述】:

我正在尝试调用我的 api 来获取 tp 的名称,但在视图中我只看到 [object promise] 并且在浏览器控制台中它看起来像是在进行无限循环

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

你知道为什么会发生这种情况以及如何纠正吗?

编辑:

【问题讨论】:

    标签: javascript node.js async-await infinite-loop http-get


    【解决方案1】:

    将api调用从html移动到组件控制器会很好。

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

    【讨论】:

    • 你的代码现在显示一个'null'并且控制台仍在无限循环
    • the console is still looping infinitely - 这是什么意思?如果您转到开发者控制台中的网络选项卡,您会看到请求吗?
    • 是无休止的请求,如果我在控制台登录我的方法 this.apiService.gettpname 我得到一个对象:{ "_isScalar": false, "source": { "_isScalar": false, "source" : { "_isScalar": false, "source": { "_isScalar": false }, "operator": { "concurrent": 1 } }, "operator": {} }, "operator": {} }跨度>
    • 当然你会用 console.log 得到结果,因为 if 是一个 observable 而不是结果。你确定你的后端有效吗?如果可以,请附上您的网络标签的屏幕截图
    • 完成了,那么如何从 observable 中提取名称?在我的后端终端中,我看到了一个 get 响应,所以我想它可以工作
    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2013-12-13
    • 1970-01-01
    相关资源
    最近更新 更多