Reputation: 37
This my html code and below in my ts code ,
<div id="address" class="bg-light rounded mt-3">
<div class="h5 font-weight-bold text-primary"> Customer Feedback </div>
<div class="d-md-flex justify-content-md-start align-items-md-center pt-3">
<div class="mr-auto"> <b>Purchase Feedback </b>
<p class="text-justify text-muted">{{description}}</p>
</div>
</div>
</div>
I am getting this feedback from an api which I am storing in localstorge , but sometime its very much possible that this.feedbackdetails.description might be null , when the data is available it works fine but data is not available it gives error something like this
this.feedbackdetails = JSON.parse(localStorage.getItem('feedback'))
if (this.feedbackdetails.description != null) {
this.description = this.feedbackdetails.description
} else {
this.description = 'NO FEEDBACK PROVIDED'
}
ErrorMsg:-
TypeError: Cannot read property 'description' of null
at GetcutomerorderdetailsComponent.push../src/app/getcutomerorderdetails/getcutomerorderdetails.component.ts.GetcutomerorderdetailsComponent.ngOnInit (main.js:1407)
at checkAndUpdateDirectiveInline (vendor.js:56990)
at checkAndUpdateNodeInline (vendor.js:65246
Is there any way to handle this ?
Upvotes: 1
Views: 621
Reputation: 1572
In your case this would be enough, since you detect existance of value of description property (regardless if it exists or not)
if (this.feedbackdetails && this.feedbackdetails.description)
or simplified:
if (this.feedbackdetails?.description)
Upvotes: 1
Reputation: 772
I would simply do:
this.feedbackdetails = JSON.parse(localStorage.getItem('feedback'))
this.description = this.feedbackdetails?.description ?? 'NO FEEDBACK PROVIDED';
this.feedbackdetails? would do the null/undefined validation and return 'NO F..' if null,
Else would check this.feedbackdetails.description, which if null/undefined, would again return 'NO F..', or the value even if it's ''/0/false.
Upvotes: 0
Reputation: 280
You can try by giving a null check in the start
this.feedbackdetails = JSON.parse(localStorage.getItem('feedback'))
if(this.feedbackdetails){
if (this.feedbackdetails.description != null) {
this.description = this.feedbackdetails.description
} else {
this.description = 'NO FEEDBACK PROVIDED'
}
}
or using ?
operator
if (this.feedbackdetails?.description != null) {
this.description = this.feedbackdetails.description
} else {
this.description = 'NO FEEDBACK PROVIDED'
}
Upvotes: 0
Reputation: 518
You can change your if to handle the lack of this.feedbackdetails.description:
if(this.feedbackdetails && this.feedbackdetails.hasOwnProperty("description"))
Upvotes: 1