[英]argument of type string | null is not assignable to parameter of type string error
When I try to get local storage records It gives following error.当我尝试获取本地存储记录时,它会出现以下错误。
"Argument of type 'string | null' is not assignable to parameter of type 'string'.\n Type 'null' is not assignable to type 'string'.",
here is the code这是代码
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
accepts an arg of type string JSON.parse
接受字符串类型的 arg
localStorage.getItem
returns an arg of type string or null (if its not found) localStorage.getItem
返回字符串类型的 arg 或 null(如果未找到)
therefore you can add a quick default value set before the parse.因此,您可以在解析之前添加一个快速的默认值集。 like so:
像这样:
const newPet = JSON.parse(localStorage.getItem('newPet') || "{}");
another option is to fetch the result from the localstorage, check that it is not null and then parse it.另一种选择是从本地存储中获取结果,检查它是否不是 null 然后解析它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.