无法阅读财产" totalPrice"未定义的

时间:2017-01-09 23:38:33

标签: angular

我的Angular 2模板上有这个代码。

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

当我在控制台中记录carts.totalPrice时,它会显示正确的值。这是对象值。

enter image description here

我怀疑这里的模板加载速度比对象快,因为它告诉我它无法读取属性。我是对的吗?

编辑:这是我获取购物车价值的方法。

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

错误堆栈跟踪。

enter image description here

2 个答案:

答案 0 :(得分:4)

试试这个:

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

答案 1 :(得分:1)

lennys的答案是完全正确的,我认为我会提出更多选择。

由于数据检索是异步的,通常意味着在数据到达之前呈现视图,就像您怀疑的那样。这意味着在渲染视图时,您的对象仍然是undefined / null

你可以有几个选择来解决这个问题。

根据具体情况,您可以在组件中初始化对象,这样就不会出现问题:

carts: Object = {};

使用安全导航操作员(?)。

{{carts?.totalPrice}}

这是一种防止属性路径中的空值和未定义值的便捷方法。视图仍然呈现,但属性路径显示为空白。

使用*ngIf (查看lennys回答)

*ngIf和安全导航操作符的主要区别在于,模板中包含*ngIf元素的部分将从DOM中完全删除,直到将存在carts中的值。