首页 > 解决方案 > 来自模板的函数调用以无限循环结束 - Angular 6

问题描述

我正在从模板调用一个函数,该函数进行async调用并在 html 中显示返回的响应。但是,此调用以无限循环结束。

我已经阅读了我们应该使用变更检测策略的解决方案,但这也无济于事。

示例.html:

<div *ngFor = "let data of hugeData; let i = index">
 <span *ngIf="getData(i) | async as variable" [innerHTML] = "variable">
</div>

sample.component.ts:

@Component({
selector : 'sample',
templateUrl : './sample.html',
changeDetection : ChangeDetectionStrategy.OnPush
})

sample.component.ts 中的函数调用:

getData(i){
 return new Promise (function (resolve,reject){
  this.makeApiCall(i).subscribe(response=>{
  this.cd.detectChanges();
  resolve(response);
  })
 })
}

makeApiCall(i)是另一个进行 API 调用并将响应作为 Observable 返回的函数调用。

在这种情况下,它会引发错误:无法读取未定义的属性“makeApiCall”。

请帮我解决这个问题。提前致谢。

标签: javascriptangular6

解决方案


this是引用在Promise参数中传递的函数,您可能想要this引用该类

一个简单的解决方案是在Promise.

前任:

return new Promise ((resolve,reject) => { ...

推荐阅读