typescript - 字符串类型的参数 | null 不能分配给类型字符串错误的参数
问题描述
当我尝试获取本地存储记录时,它会出现以下错误。
"Argument of type 'string | null' is not assignable to parameter of type 'string'.\n Type 'null' is not assignable to type 'string'.",
这是代码
this.service.getAllPets(this.CatDog).subscribe(
data => {
this.pets = data;
console.log(data);
// tslint:disable-next-line:no-bitwise
const newPet = JSON.parse(localStorage.getItem('newPet'));
if (newPet){
this.pets = [newPet, ...this.pets];
}
console.log(this.route.snapshot.url.toString());
}, error => {
console.log('httperror:');
console.log(error);
}
);
解决方案
JSON.parse
接受字符串类型的 arg
localStorage.getItem
返回字符串类型的 arg 或 null(如果未找到)
因此,您可以在解析之前添加一个快速的默认值集。像这样:
const newPet = JSON.parse(localStorage.getItem('newPet') || "{}");
另一种选择是从本地存储中获取结果,检查它是否不为空,然后解析它。
推荐阅读
- http - 纯 sh + telnet 中的 HTTP POST 文件:没有 curl,没有 wget
- python - 如何测试编辑数据库的 Flask 视图?
- javascript - 从填充的 var 获取 ajax 输出并在加载页面时打印出来
- javascript - 是否可以使 getter 方法异步?
- sql - 插入到带有日期时间列的表中
- hadoop - 从 HDFS 加载到 S3 时如何解压缩文件?
- eclipse - 我正在尝试在 Eclipse 中设置一个新项目给出错误消息:设置项目
- python - aws lambda - 找不到 libmagic
- javascript - setTimeout 在第三次调用时覆盖了我的代码
- gps - 如何使用 arduino 将以太网模块连接到 gps 模块