I'm using Angular 14 and currently there is no ngrx
state management in the application. I need to retain the value of a variable even if the user refreshes the page. I've two components. In first component I'm setting some value in localStorage and in the second component I'm simply getting that value:
component-1
ngOnInit() {
localStorage.setItem('myKey', 'Apple')
}
And in the second component I'm simply reading the value and after that I also need to clear the localStorage:
component-2
myFruit: string='';
ngOnInit() {
this.myFruit = localStorage.getItem('myKey');
...
...
localStorage.clear();
console.log(this.myFruit); // OUTPUT: ERROR TypeError: this.myFruit is null
}
I have to clear the localStorage. That's why I'm setting the value before clearing it. Please correct my mistake. I need to retain the value of myFruit
even if the user refreshes the page.
CodePudding user response:
Look at using session storage - I am unclear why you have to clear local storage, but if you're not going to pass this data to a database, and you don't have access to your browser persistent storage, then there is no possible way