Reputation: 105
I am having trouble on my angular program. I always get the undefined error variable.
This is defining the variable in my component
export class OrdersDetailComponent implements OnInit {
title = 'Order';
menus = [];
order: Array<{
code: String
}>;
ngOnInit() {
var id = this.route.params.subscribe(params => {
var id = params['id'];
if (!id)
return;
this.api.post('orders/get', { id: id })
.subscribe((data) => {
this.order = data.order;
this.menus = data.menus;
},
response => {
if (response.status == 404) {
this.router.navigate(['NotFound']);
}
});
});
}
And this my html
<h3>{{ title }} #{{order.code}}</h3>
I am always get error in console
ERROR TypeError: Cannot read property 'code' of undefined
at Object.eval [as updateRenderer] (OrdersDetailComponent.html:3)
at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13131)
at checkAndUpdateView (core.es5.js:12275)
at callViewAction (core.es5.js:12638)
at execComponentViewsAction (core.es5.js:12570)
at checkAndUpdateView (core.es5.js:12276)
at callViewAction (core.es5.js:12638)
at execEmbeddedViewsAction (core.es5.js:12596)
at checkAndUpdateView (core.es5.js:12271)
at callViewAction (core.es5.js:12638)
Thanks for your help.
Upvotes: 1
Views: 15091
Reputation: 1
you can create a function to check undefined variables.
` SafetyCheck(fn:any)
{
try{
return fn();
}catch(e){
console.log(e);
return undefined;
}
}`
then change this
this.order = data.order; this.menus = data.menus;
for this
this.order = SafetyCheck(()=>data.order);
this.order = SafetyCheck(()=>data.menus);
Upvotes: 0
Reputation: 222522
you are making a asynchronous request, initially data will be undefined, use a safe navigation operator
(Safe navigation operator can be used to prevent Angular from throwing errors, when trying to access object properties of objects that don't exist) to check if the results exists and then access the data
<h3>{{ title }} #{{order?.code}}</h3>
Edit
Create an class as follows and save it as order.ts,
export class Order{
code: string;
}
then import in your component as,
order : Order[];
Upvotes: 10