Per Per - 1 month ago 7
TypeScript Question

Update view after http subscribe, angular

ngOnInit(): void {
// Make the HTTP request:
this.http.get('/api_admin/user').subscribe(data => {
// Read the result field from the JSON response.
this.results = data;

});
}


view:

<ul>
<li *ngFor="let project of results.name"></li>
</ul>


Gives console error:

ERROR TypeError: Cannot read property 'name' of undefined


Do I somehow need to "tell" the view that a value has arrived?

Answer Source

Your data is undefined, while it wants to use in the template. Or you can set the default value for the results or you can use ngIf to show that part only when the data was arrived.

Set default value for results

results: any = { name: [] };

or use ngIf

<ul *ngIf="results">
  <li *ngFor="let project of results.name"></li>
</ul>