首页 > 解决方案 > 如何在本地存储上进行活动

问题描述

我想在角度本地存储中存储一些应用程序变量(如用户名和 apikey)。但是当我更改这些值时,我想查看我的用户界面更改(导航栏上的登录按钮)。实际上,当值发生变化时,我无法捕捉到事件。

因此,我尝试在具有从 rxjs 导入的主题属性和更改属性的原始 angular localstorage 之上创建一个新服务。所以我有这个类(部分来自stackoverflow)

import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from "rxjs";
import { share } from 'rxjs/operators';

@Injectable()
export class StorageService implements OnDestroy {
  private onSubject = new Subject<{ key: string, value: any }>();
  public changes = this.onSubject.asObservable().pipe(share());

  constructor() {
    this.start();
  }

  ngOnDestroy() {
    this.stop();
  }

  public getStorage() {
    let s = [];
    for (let i = 0; i < localStorage.length; i++) {
      s.push({
        key: localStorage.key(i),
        value: JSON.parse(<string>localStorage.getItem(<string>localStorage.key(i)))
      });
    }
    return s;
  }

  public store(key: string, data: any): void {
    localStorage.setItem(key, JSON.stringify(data));
    // the local application doesn't seem to catch changes to localStorage...
    this.onSubject.next({key: key, value: data})
  }

  public clear(key: string) {
    localStorage.removeItem(key);
    // the local application doesn't seem to catch changes to localStorage...
    this.onSubject.next({key: key, value: null});
  }


  private start(): void {
    window.addEventListener("storage", this.storageEventListener.bind(this));
  }

  private storageEventListener(event: StorageEvent) {
    if (event.storageArea == localStorage) {
      let v;
      try {
        if (event.newValue !== null) {
          v = JSON.parse(event.newValue);
        }
      } catch (e) {
        v = event.newValue;
      }
      // @ts-ignore
      this.onSubject.next({key: event.key, value: v});
    }
  }

  private stop(): void {
    window.removeEventListener("storage", this.storageEventListener.bind(this));
    this.onSubject.complete();
  }
}

在我的登录组件中,我有这个:

      const storageService = new StorageService()
      if (res.status === 200) {
        storageService.store('logged',JSON.stringify(await res.json()))
        this.redirectAfterLogin()
      }else {
        storageService.clear('logged')
      }

在我的导航栏组件中,我尝试了这个:

  ngOnInit(): void {
    window.addEventListener('storage',function (param){
      console.log('here ? key is :'+param.key)
    })
  }

标签: angulartypescript

解决方案


推荐阅读