I am currently working on setting the expiry for a token in local storage by utilizing the angular async local storage module.
import { AsyncLocalStorage } from 'angular-async-local-storage';
const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
this.localStorage.setItem('expires_at', expiresAt).subscribe(() => {});
Subsequently, I have created a function that is invoked when a user logs in to verify if the token remains valid:
get isAuthenticated(): boolean {
let res;
this.localStorage.getItem('expires_at')
.subscribe((val) => {
let expiresAt = JSON.parse(val);
res = (expiresAt && this.loggedIn) ? (new Date().getTime() < expiresAt) : false;
});
return res;
}
The issue at hand lies with the fact that localStorage.getItem() returns an Observable. Consequently, when we call .subscribe on the observable, it operates asynchronously, causing the code to continue running without pausing until the result is available. As a result, the return statement executes prematurely, leading to undefined behavior for the variable res, as the subscribe arrow function has not finished executing.
Given this challenge, I seek advice on the most effective solution. One potential approach I considered was attempting to block the execution until the result is ready, but this contradicts the purpose of using the ASYNC local storage module. Perhaps what I require is a straightforward synchronous local storage module instead? However, is this methodology deemed ill-advised or bad practice? I would greatly appreciate any guidance or insights on this matter. Thank you!