I have a component that takes the URL param, call API and displays the data. Most basic and typically sample:
ngOnInit() {
this.route.params.subscribe( params => {
const id = params.id;
this.loadAssets(id);
});
}
loadAssets(id)
{
this.apiService.getAssetGroup(id).subscribe((data) => {
this.assetGroup = data;
this.assetSubGroupList = data.assetSubGroupList;
console.log(this.assetGroup);
});
}
In my html i do a simple loop:
<div class="row">
<div class="col-sm-12 col-lg-12">
<div *ngFor="let subGroup of assetGroup.assetSubGroupList">
<div>SubGroup: {{subGroup.name}}</div>
<div *ngFor="let asset of subGroup.assetList">Asset: {{asset.name}}</div>
</div>
</div>
</div>
I guess this is some of to most common scenarios in web development. However, I get the following error:
Cannot read property 'assetSubGroupList' of undefined at Object.eval [as updateDirectives] (AssetsComponent.html:5)
My best guess is this is because when the page is loaded assetGroup is null. The page actually ends working after the data is loaded, but i dont want the first error. I am thinking there must be some standard way of handling this scenario in Angular. Do you always initialize variables, use ngIf or even something smarter?