Reputation: 59
I am doing a normal http get request in my component and i am showing the results in the html, everything is working but when i open the console i get the error. 'Cannot read property 'content' of undefined.
<div class="container myPadding">
<div class="form-row justify-content-center">
<h1>Substances</h1>
</div>
<div class="form-row justify-content-center">
<p class="alert alert-info">
Total Substances registered: ({{ substanceList.totalElements }})
</p>
</div>
<a>
<table class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Substance Name</th>
</tr>
</thead>
<tbody *ngFor="let response of substanceList.content | slice:0:99">
<tr>
<td>{{response.neo4jId}}</td>
<td>{{response.substanceName}}</td>
</tr>
</tbody>
</table>
</a>
and ts file
export class SubstancesComponent implements OnInit, OnDestroy {
substanceList: any;
subscription: Subscription;
constructor(private http: HttpClient, private drugService: DrugsService) { }
ngOnInit() {
this.getAllSubstances();
}
getAllSubstances() {
this.subscription = this.drugService.getSubstances().subscribe(response => {
this.substanceList = response;
console.log(this.substanceList);
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
and this is the function in my service
getSubstances(): any {
return this.http.get(environment.substancesUrl);
}
The result in the browser is the one i want to have but this error appears in the console, i would like to understand why this error occurs and how i can solve this.
Upvotes: 0
Views: 373
Reputation: 1771
You want to add ?
s in front of all your object properties, e.g. {{ substanceList?.totalElements }}
which prevents issues associated with trying to find the key totalElements
on an object which is still being returned by the get request.
You will also likely want to add the async pipe to any variables which are populated as a result of an asynchronous call to ensure the data is only rendered to the screen once it is available (and does not briefly display undefined
for example), e.g. {{ substanceList?.totalElements | async }}
Upvotes: 1
Reputation: 455
You can not directly access the elements of an object in the HTML page.
Please do the following changes:
<tbody *ngFor="let response of substanceList && substanceList.content | slice:0:99">
OR
<tbody *ngFor="let response of substanceList?.content | slice:0:99">
Upvotes: 1