具有sessionStorage和service的Angular全局变量

时间:2018-06-27 02:31:25

标签: angular session-storage

我创建了一个服务,以便将全局变量保存为angular。

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
@Injectable()
@Injectable({
  providedIn: "root"
})
export class SharedService {
  private experimentIdSource = new BehaviorSubject("noId");
  currentExperimentId = this.experimentIdSource.asObservable();

  constructor() {}

  changeExperimentId(experimentId: string) {
    this.experimentIdSource.next(experimentId);
  }
}

像这样,我可以在另一个组件中使用它,并查看变量是否已更改。只需将其写入ngOnInit()的正确组件中即可:

  ngOnInit() {
    this.shared.currentExperimentId.subscribe(
      currentExperimentId => (this.currentExperimentId = currentExperimentId)
    );
  }

实际上,根据变量的值,我使用 ngIf =“ currentExperimentId!=='noId'”

在html中显示一些除法/元素

但是,当我重新加载页面时,该变量被重新初始化,并且不再看到除法/元素。 * 因此,我将变量像这样存储在sessionStorage中:

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
@Injectable()
@Injectable({
  providedIn: "root"
})
export class SharedService {
  previousExperimentId = sessionStorage.getItem("currentExperimentId")
    ? sessionStorage.getItem("currentExperimentId")
    : "noId";
  private experimentIdSource = new BehaviorSubject(this.previousExperimentId);
  currentExperimentId = this.experimentIdSource.asObservable();

  constructor() {}

  changeExperimentId(experimentId: string) {
    sessionStorage.setItem("currentExperimentId", experimentId);
    this.experimentIdSource.next(experimentId);
  }
}

我想知道是否还有其他方法或更好的方法?因为看起来就像在修补东西

0 个答案:

没有答案