Issue
I got an error ERROR TypeError: Cannot read property 'name' of undefined
I have a service that retrieves data from the storage and a homepage that calls the service and displays the data.
storage.service.ts
async initilizeData() {
this.data = await this.storage.get('myData')
}
getData() : MyData {
return this.data
}
home.page.ts
data: MyData
async ngOnInit() {
this.storageService.initializeData()
this.data = this.storageService.getData()
console.log(this.data)
}
home.page.html
<ion-text>{{data.name}}</ion-text>
<ion-text>{{data.amount}}</ion-text>
The console.log() inside ngOnInit() does log out the data for me but in the HTML page both data.name and data.amount seems to be undefined (I knew since when I put *ngIf="!data == null" around the code, the error disappeared.)
Thank you for all the answers :)
Solution
One way to do that would be to wrap the data using an ngIf
, like this:
<ng-container *ngIf="data">
<ion-text>{{ data.name }}</ion-text>
<ion-text>{{ data.amount }}</ion-text>
</ng-container>
The content won't be displayed until data
is initialized.
Another way to avoid this would be by using the safe navigation operator, like this:
<ion-text>{{ data?.name }}</ion-text>
<ion-text>{{ data?.amount }}</ion-text>
In this case, Angular will not try to access data.name
and data.amount
if data
is null or undefined. Please keep in mind that this approach will still render the ion-text
elements, but they will be empty until data
is initialized.
Answered By - sebaferreras
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.