angular - 如何在 Angular 2 中从本地存储订阅项目并在更改时获取值

标签 angular typescript

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

最佳答案

对于一个基本的想法,这是如何完成的。

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


编写全局服务:

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');
 }
}

用法:

  • 此处的任何更改
@Component({})
export class SomeComponent {
  constructor(private globalSrv: GlobalService){}

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

关于angular - 如何在 Angular 2 中从本地存储订阅项目并在更改时获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541783/

相关文章:

angular - ng-bootstrap 预先输入选定的对象

angular - 如何将 AbstractControl 转换为模板中的 FormControl?

javascript - 在 Angular 中显示 ContentFul RichText

javascript - 我可以在 typescript 中使用 handsontable 吗

javascript - 迭代枚举时如何排除命名空间函数?

Angularfire 2 和 Ionic 2

javascript - 如何更改传单中的标记颜色?

带有 @nguniversal 的 Angular SSR 和用于 PostCSS 支持的自定义 webpack

angular - Material 日期-fns 适配器

android - 无法使用 TypeScript 构建 NativeScript 自定义模块