Angular 服务获取 json 数据

Angular Service get json data

我正在尝试使用 Angular 8:

上的此代码从本地存储中获取一些已保存的 json 数据
getState(key: string) {
  return this.state$.pipe(map(obj => obj[key]));
} 

但是当我这样做时:

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

它没有return 解析数据。

但是当我这样做时:

var result = JSON.parse(localStorage.getItem('state1'));

return是我想要的结果。

我的问题是:

如何修改此方法:

getState(key: string) {
  return this.state$.pipe(map(obj => obj[key]));
} 

...这样 return 结果会像 JSON.parse 吗?

这里是整个服务代码:

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

}

根据 $ 符号和它后面的 .pipe,看起来 this.state$ 给你一个可观察的。所以你必须订阅它。如果您不订阅,则看不到数据。

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

但是要小心,如果像你说的那样 this.state$ 是一个 BehaviorSubject,你必须在你的 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();
  }
}

如果你只想要当前值,如果值发生变化而不被再次调用,你也可以获取它的同步值:

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