Cannot read property “totalPrice” of undefined

2020-01-29 03:23发布

问题:

I have this code on my Angular 2 template.

<td class="hidden-xs text-center"><strong>Total: &#8369; {{carts.totalPrice}}</strong></td>

When I log carts.totalPrice in console, it shows the correct value. Here is the object value.

What I suspect here is that the template loads faster than the object that's why it tells me that it cannot read the property. Am I right?

EDIT: This is my method on getting the carts value.

getItems(){
    this._cartService.getCartItems(localStorage.getItem('currentUserId'))
        .subscribe((cart) => {
            this.cartItems = cart.products;
            // this.totalPrice = cart.totalPrice;
            this.carts = cart;
            console.log(this.carts)
        },
        (err) => console.log(err));
}

Error stack trace.

回答1:

Try this:

<td *ngIf="carts" class="hidden-xs text-center"><strong>Total: &#8369; {{carts.totalPrice}}</strong></td>


回答2:

lennys answer is completely correct, I thought that I would present a couple more options.

Since the retrieval of data is asynchronous, it usually means that the view is rendered before data has arrived, just as you suspected. This then means that at the point when the view is rendered your object is still undefined/ null.

You would have a few options to solve this.

  • Initialize your Object
  • Use the safe navigation operator
  • Use *ngIf

Depending on the case, it can help that you simply initialize your object in your component, so that it will not be undefined:

carts: Object = {};

Use the safe navigation operator (?).

{{carts?.totalPrice}}

This is a convenient way to guard against null and undefined values in property paths. The view still renders but the property path is displayed as blank.


Use *ngIf (check lennys answer)

The main difference with *ngIf and the safe navigation operator is, that the part from the template which is wrapped inside the element with *ngIf, will be completely removed from the DOM, until there will be values in carts.



标签: angular