I am trying to get some saved json data from localstorage with this code on Angular 8:
getState(key: string) {
return this.state$.pipe(map(obj => obj[key]));
}
but when I do this:
console.log(this.appState.getState('state1'));
It doesn't return the data parsed.
But when I do this:
var result = JSON.parse(localStorage.getItem('state1'));
It returns the result I wanted.
My question is:
How can I modify this method:
getState(key: string) {
return this.state$.pipe(map(obj => obj[key]));
}
...so that it return the results like JSON.parse would?
Here is the whole service code:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AppStateService {
private appState = {};
private state$;
constructor() {
this.state$ = new BehaviorSubject(this.appState);
}
initState() {
Object.keys(localStorage).forEach(key => {
if (localStorage[key][0] === '{') { this.appState[key] = JSON.parse(localStorage[key]);
} else {
this.appState[key] = localStorage[key];
}
});
this.state$.next(this.appState);
}
setState(key: string, value: any, persist: boolean = false) {
this.appState[key] = value;
this.state$.next(this.appState);
if (persist) {
if (typeof value === 'object') { localStorage[key] = JSON.stringify(value);
} else {
localStorage[key] = value;
}
}
}
getState(key: string) {
return this.state$.pipe(map(obj => obj[key]));
}
}
this.state$?this.state$?