Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度2:在模板循环中重复异步调用_Angular_Asynchronous - Fatal编程技术网

Angular 角度2:在模板循环中重复异步调用

Angular 角度2:在模板循环中重复异步调用,angular,asynchronous,Angular,Asynchronous,我有一个带有ngFor的模板,该模板通过一个异步可观察对象接收数据: <div *ngFor="let result of data.results"> <div> <img [src]="parseSrc(result.src)" alt="{{ getCaption(result.id) | async }}" /> {{ getCaption(result.id) | async }} </div> </div&

我有一个带有
ngFor
的模板,该模板通过一个异步可观察对象接收数据:

<div *ngFor="let result of data.results">
  <div>
    <img [src]="parseSrc(result.src)" alt="{{ getCaption(result.id) | async }}" />
    {{ getCaption(result.id) | async }}
  </div>
</div>
打两次电话可以吗?我觉得调用该函数两次是多余的,而且占用大量内存。其他的选择是什么?我在想,在模板中创建一个变量会很好,但这不是一个方便的方法。由于这是另一个异步调用的结果,因此在控制器代码中执行此逻辑并不理想,我觉得应该有一种相对优雅的方式在模板中执行这两个相同的调用


注意:这是一个精心设计的示例。

您可以将其包装在
ngIf
中,并使用语法将其绑定到本地值,如下所示:

<div *ngIf="getCaption(result.id) | async as caption">
    <img [src]="parseSrc(result.src)" alt="{{ caption }}" />
    {{ caption }}
</div>

{{caption}}

您可以将其包装在
ngIf
中,并使用语法将其绑定到本地值,如下所示:

<div *ngIf="getCaption(result.id) | async as caption">
    <img [src]="parseSrc(result.src)" alt="{{ caption }}" />
    {{ caption }}
</div>

{{caption}}