I have an Angular service that successfully stores the key and value but fails to retrieve it. Below is the code:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() {}
// Store the value - (Note: This code works fine. The key is userData and it stores an array of user credentials as value )
async store(storageKey: string, value: any) {
localStorage.setItem('key', storageKey);
localStorage.setItem('value', value);
}
// Get the value - Here I provide the userData as key but I get a null value. If put key in "key" then I get an error. I have verified with console.log(key) that accurate key is passed to retrieve the value.
async get(key: string) {
const ret = localStorage.getItem(key);
return JSON.parse(ret);
}
}
The following code solved for it. Basically, I had to add .then after the storageService.get function.
storageService.get('userData').then(res => {
if (res !== null) {
return true;
} else {
router.navigate(['login']);
return false;
}
});