1

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.

2 Answers 2

10

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[];
Sign up to request clarification or add additional context in comments.

2 Comments

not work. in vscode i have error [Angular] Identifier 'code' is not defined. 'Array' does not contain such a member and in concole i have error ERROR CONTEXT
Oh yeah success. Thanks for your help.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.