I am trying to save a value in localStorage and to retrieve it on refresh. I have created a local-storage service and I set a local storage value by calling the service.
on refresh I want to retrieve the value so I have the following in my appComponent ngOnInit..
ngOnInit() {
// Service which returns undefined
console.log(this.ls.getLocalStorage('test'))
// local which returns value...
console.log(localStorage.getItem('test'));
}
and in my local-storage-service I have the following.
getLocalStorage(k) {
console.log(k);
localStorage.getItem(k);
}
the first one in my onInit returns undefined, yet the second one returns the correct value.
Why is this happening and is there a way to resolve it?
Thanks
You are not returning any value within your function. Please add the return
keyword.
getLocalStorage(k) {
console.log(k);
return localStorage.getItem(k);
}
I think you missed a return
statement
Your method has to look like this:
getLocalStorage(k) {
return localStorage.getItem(k);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.