简体   繁体   English

如何在 angular 2 中从 localstorage 订阅项目,并在更改时获取值

[英]how to subscribe an item from localstorage in angular 2 and when changed, get value

我正在尝试使用 angular 2 创建一个应用程序,我的问题是如何从本地存储订阅项目...我知道我必须使用一项服务,只能从任何地方通过此服务访问 LocalStorage,但我不知道如何做到这一点。

For a basic Idea this is how it can be done.对于一个基本的想法,这是如何做到的。

Just need to write the correct Import paths accotding to your configuration只需要根据您的配置编写正确的导入路径


Write a global service:编写一个全局服务:

import {BehaviorSubject} from 'rxjs';   

@Injectable({providedIn: 'root'})
export class GlobalService {
 itemValue = new BehaviorSubject(this.theItem);

 set theItem(value) {
   this.itemValue.next(value); // this will make sure to tell every subscriber about the change.
   localStorage.setItem('theItem', value);
 }

 get theItem() {
   return localStorage.getItem('theItem');
 }
}

Usage:用法:

  • Any change here这里有任何变化
@Component({})
export class SomeComponent {
  constructor(private globalSrv: GlobalService){}

  someEvent() {
    this.globalSrv.theItem = 'someValue'; // this change will broadcast to every subscriber like below component
  }
}
  • Will Reflect Here会反映在这里
@Component({})
export class AnotherComponent {
  constructor(private globalSrv: GlobalService){
    
      globalSrv.itemValue.subscribe((nextValue) => {
         alert(nextValue);  // this will happen on every change
      })
  
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM