Issue
I am storing data in the session storage with an expiry date :
private saveSessionData<T>(key: string, value: T) {
const item = {
value: value,
expiry: Date.now() + 10 * 60000 // 10 minutes from now
}
sessionStorage.setItem(key, JSON.stringify(item));
}
I have an other function to access those data, that will return null if the data I try to access is expired :
private async getSessionData<T>(key: string): Promise<T | null> {
const itemStr = sessionStorage.getItem(key);
const item = JSON.parse(itemStr);
if (Date.now() > item.expiry) {
console.log('CONSOLE NULL');
await this.alertService('OBJ EXPIRED');
return null;
}
return item.value;
}
I access those data like that :
getMyObj$ (): Observable<MyObj| null> {
return from(this.getSessionData<MyObj>(this._myObj))
.pipe(
takeWhile(myObj => myObj != null),
tap(x => console.log('getting my Obj')
);
}
In my View, I'm using the | async to show myObj with a two way data binding :
<div *ngIf="!!(getMyObj$ | async) as obj">
<div>{{ obj }}</div>
</div>
My thought would be that my console show me the getting my Obj again and again until the expiry date is overdue, and then to see the alert message : OBJ EXPIRED with the console message CONSOLE NULL once.
But currently, after the getting my Obj message, I have infinite CONSOLE NULL messages (that makes my browser crash) and the alert event is never shown.
Any one got any idea ? I have no idea what could makes that crash like that.
Solution
This is probably because of angular change detection, causing it to repeatedly call that method and subscribe to a new observable each time. You should instead create the observable once and share it:
this.getMyObj$ =
interval(1000).pipe(
concatMap(() => this.getSessionData<MyObj>(this._myObj)),
takeWhile(myObj => myObj != null),
tap(x => console.log('getting my Obj'),
shareReplay(1)
);
Answered By - NickL
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.