'Angular ngFor not displaying async data
Why can't I display the this.countries$ list in the select element?
component.ts
countries$! : Observable<String[]>;
constructor(private statisticService : StatisticService, private fb : FormBuilder) {
this.getAllCountries();
}
getAllCountries() : void {
this.statisticService.getAllCountries().subscribe((countries) => {
this.countries$ = of(countries);
console.log(countries)
});
}
The getAllCountries method in the service returns an Observable of an array of Strings:
getAllCountries(): Observable<String[]> {
return this.http.get<String[]>('http://localhost:8080/countries');
}
This is how I'm presenting the data in HTML:
<select>
<option *ngFor="let cntry of countries$ | async" [value]="cntry">
{{ cntry }}
</option>
</select>
When I console.log(this.countries$) after the subscribe method, all countries are correctly retrieved but they don't get displayed in the select element as it should be. The select element correcly presents 233 options (number of countries) but all of the options are blank.
What am I missing here? Thanks!
Solution 1:[1]
in ts file
export interface Person {
name: string;
place: string;
}
myself$: Observable<Person[]>;
<ul *ngIf="myself$ | async as myselfs">
<li *ngFor="let myself of myselfs; index as i">{{ myself.name }}</li>
</ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
