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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37541783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:32:32  来源:igfitidea点击:

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

angulartypescript

提问by Ankit Singh

I'm trying to create an application with angular 2, and my problem is how to subscribe an item from local storage... I know I must use a service, only access LocalStorage through this service from everywhere, but I don't know how this can be done.

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

回答by Ankit Singh

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({provideIn: '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
      })

  }
}