[Fixed] Angular Variable Error Undefined


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)

        this.api.post('orders/get', { id: id })
            .subscribe((data) => {
                this.order = data.order;
                this.menus = data.menus;
            response => {
                if (response.status == 404) {

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.


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>


Create an class as follows and save it as order.ts,

export class Order{
    code: string;

then import in your component as,

order : Order[];

Leave a Reply

(*) Required, Your email will not be published