4

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);
  }
);

1 Answer 1

9

JSON.parse accepts an arg of type string

localStorage.getItem returns an arg of type string or null (if its not found)

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.