How can I use async pipe when calling service method from template?
This code works:
<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
}
but I would like to avoid assigning value to filenames (this.filenames = this.importService.list();
) and call method directly from html:
<div *ngFor="let filename of importService.list() | async">
<div>{{filename}}</div>
</div>
But this execute unlimited request to server. (As I would call importService.list().subscribe()
in endless loop).
I also tried this (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>
But none works.
This Github issue described exactly the same thing. I hope something has changed in year and half and this could be done.
Edited:
Desired effect can be achieved with several approaches.
First:
<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);
}
Second, more effective (shorter):
<div *ngFor="let filename of filenames | async">
<div>{{filename}}</div>
</div>
public filenames: Observable<string[]>;
constructor(public importService: ImportService)
{
this.filenames = this.importService.list();
}
and third even shorter (what I want to achieve):
constructor(public importService: ImportService) { }
<div *ngFor="let filename of importService.list() | async">
<div>{{filename}}</div>
</div>