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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With