angular - TypeScript 中的数组为空
问题描述
我有这个数组:
productCarts: ProductModel[] = [];
当我在 ngInit 中调用此方法时出现错误Cannot read property 'length' of null
:
addProductFromLocalStorage() {
if (this.productCarts.length == 0) {
this.productCarts = this.fromLocalStorage;
}
}
解决方案:我的本地存储返回空值,我有异常。
解决方案
尝试这个 :
addProductFromLocalStorage() {
if (!this.productCarts || this.productCarts.length === 0) {
this.productCarts = this.fromLocalStorage;
}
}
!this.productCarts
这将检查 null 和未定义的值
推荐阅读
- python - Python多处理:有效地只保存最好的运行
- apache-kafka - kafkaRDD next() 慢
- python - Python 中的 IMDB 网页抓取
- python - Django 查询所有记录并注释给定日期和布尔状态之间的天数,直到日期布尔值更改
- html - 如何使右侧的 col-md-3 在 html bootstrap 4 中对齐
- javascript - 是否可以返回带有对象属性名称的数组?它被连线要求打印没有''的字符串
- python - 不能使用来自opencv的SIFT算法
- spring-boot - 无法在容器化 Docker 应用程序中读取用户上传的文件
- numpy - 扩展尺寸
- c# - 来自字节的字符串中的字节不等于原始字节