字符串类型的参数 | null 不可分配给字符串类型的参数错误

vin*_*i96 1 typescript angular-local-storage angular11

当我尝试获取本地存储记录时,它给出以下错误。

"Argument of type 'string | null' is not assignable to parameter of type 'string'.\n  Type 'null' is not assignable to type 'string'.",
Run Code Online (Sandbox Code Playgroud)

这是代码

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);
  }
);
Run Code Online (Sandbox Code Playgroud)

Yuv*_*val 6

JSON.parse接受字符串类型的 arg

localStorage.getItem返回 string 类型的 arg 或 null(如果未找到)

因此,您可以在解析之前添加一个快速默认值集。像这样:

const newPet = JSON.parse(localStorage.getItem('newPet') || "{}");
Run Code Online (Sandbox Code Playgroud)

另一种选择是从本地存储中获取结果,检查它是否不为空,然后解析它。