从模板调用服务方法时如何使用异步管道?
此代码有效:
<div *ngFor="let filename of filenames | async">
<div>{{filename}}</div>
</div>
//code behind
constructor(public importService: ImportService)
{
this.filenames = this.importService.list(); //returns Observable - from http.get
}
但我想避免为文件名(this.filenames = this.importService.list();
)赋值并直接从html调用方法:
<div *ngFor="let filename of importService.list() | async">
<div>{{filename}}</div>
</div>
但是这会对服务器执行无限制的请求。 (正如我在无限循环中呼叫importService.list().subscribe()
)。
我也试过这个(source for ideas):
<div *ngFor="let filename of (o = (importService.list() | async))">
<div>{{filename}}</div>
</div>
<div *ngFor="let filename of (o = (importService.list()) | async)">
<div>{{filename}}</div>
</div>
<div *ngIf="importService.list(); let o">
<div *ngFor="let filename of o | async">
<div>{{filename}}</div>
</div>
</div>
但没有效果。
这个Github issue描述的完全相同。我希望事情在一年半内发生了变化,这可以做到。
编辑:
用几种方法可以达到预期的效果
第一:
<div *ngFor="let filename of filenames">
<div>{{filename}}</div>
</div>
public filenames: string[];
constructor(public importService: ImportService)
{
this.importService.list().subscribe(res => this.filenames = res);
}
第二,更有效(更短):
<div *ngFor="let filename of filenames | async">
<div>{{filename}}</div>
</div>
public filenames: Observable<string[]>;
constructor(public importService: ImportService)
{
this.filenames = this.importService.list();
}
,第三甚至更短(我想要实现的目标):
constructor(public importService: ImportService) { }
<div *ngFor="let filename of importService.list() | async">
<div>{{filename}}</div>
</div>