When using Angular with TypeScript, I have the following component class:
@Injectable()
@Component({
selector: 'app-mycomponent',
templateUrl: './mycomponent.component.html'
})
export class MyComponent implements OnInit{
public myList : any[] = [];
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get("url").subscribe(result => {
this.myList= result;
}, error => console.log(error));
}
getSubitem(id){
return this.http.get("url/"+id).subscribe(result => {
return result;
}, error => console.error(error));
}
}
And here is the corresponding HTML snippet:
<table>
<thead>
<tr>
<th>ID</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of myList">
<td>{{item.id}}</td>
<td>{{(getSubitem(item.id) | async)}}</td>
</tr>
</tbody>
After starting the app and navigating to that view, myList
loads and displays correctly. However, the getSubitem
function is being triggered infinitely, causing the browser to crash.
How can I ensure that getSubitem
is only called once for each item in the MyList
array and that the correct information is displayed?