user11832840
user11832840

Reputation:

Angular Service get json data

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]));
  }

}

Upvotes: 0

Views: 501

Answers (1)

Random
Random

Reputation: 3236

according to the $ notation and the .pipe after it, it looks like this.state$ gives you an observable. So you have to subscribe to it. If you don't subscribe, you don't see the data.

this.appState.getState('state1').subscribe(result => {
  console.log(result);
});

But be careful, if as you said this.state$ is a BehaviorSubject, you have to manually unsubscribe to it in your ngOnDestroy:

private mySubscription: Subscription;

myMethod() {
  this.mySubscription = this.appState.getState('state1').subscribe(result => {
    console.log(result);
  });
}

ngOnDestroy() {
  if(this.mySubscription) { // must check it if you don't subscribe in your constructor. If you do it in your constructor, no need to check if it is defined.
    this.mySubscription.unsubscribe();
  }
}

If you only want the current value, without being called again if the value change, you can get its synchronous value too:

console.log(this.appState.getState('state1').value);

Upvotes: 1

Related Questions