如何在angular2中订阅localstorage中的项目,当更改时,获取值

Ali*_*ade 5 typescript angular

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

Ank*_*ngh 22

对于一个基本的想法,这是如何做到的.

只需要根据您的配置编写正确的导入路径


写一个全球服务:

import {Subject} from 'rxjs/Subject';   

@Injectable()
export class GlobalService {
 itemValue = new Subject();

 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');
 }
}
Run Code Online (Sandbox Code Playgroud)

引导此服务:

bootstrap(YourApp, [GlobalService]);
Run Code Online (Sandbox Code Playgroud)

用法:

  • 改变这里

@Component({})
export class SomeComponent {
  constructor(private globalSrv: GlobalService){}

  someEvent() {
    this.globalSrv.theItem = 'someValue'; // this change will broadcast to every subscriber like below component
  }
}
Run Code Online (Sandbox Code Playgroud)
  • 会反映在这里

@Component({})
export class AnotherComponent {
  constructor(private globalSrv: GlobalService){

      globalSrv.itemValue.subscribe((nextValue) => {
         alert(nextValue);  // this will happen on every change
      })

  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我假设您没有默认值,要使用`BehaviorSubject`,您需要定义一个默认值。 (2认同)