首页 > 解决方案 > TypeScript 中的数组为空

问题描述

我有这个数组:

productCarts: ProductModel[] = [];

当我在 ngInit 中调用此方法时出现错误Cannot read property 'length' of null

addProductFromLocalStorage() {

            if (this.productCarts.length == 0) {
                this.productCarts  = this.fromLocalStorage;  
            } 
    }

解决方案:我的本地存储返回空值,我有异常。

标签: angulartypescript

解决方案


尝试这个 :

addProductFromLocalStorage() {

            if (!this.productCarts || this.productCarts.length === 0) {
                this.productCarts  = this.fromLocalStorage;  
            } 
    }

!this.productCarts 这将检查 null 和未定义的值


推荐阅读