如何在angular-2-local-storage中订阅setItems $ Observable

时间:2017-05-31 14:40:51

标签: angular angular2-directives angular2-observables angular-local-storage

我正在使用angular-2-local-storage,它有一个可观察到的setItems $,我正在尝试...观察,在指令中使用以下代码:

/** app-theme.directive.ts **/

import { Directive, ElementRef, Input } from '@angular/core';
import { UserSettings } from './core/user-settings';
import { LocalStorageService } from 'angular-2-local-storage';

@Directive({
  selector: '[appTheme]'
})
export class AppThemeDirective {
  constructor(el: ElementRef, localStorageService: LocalStorageService) {
    localStorageService.setItems$.subscribe(function(x: any) {
      console.log('subscribed', x);
    });
  }

}

本地存储在我的代码中正在更新并保持足够好,但是没有观察到更新并且记录到控制台。我错过了任何明显的问题?

2 个答案:

答案 0 :(得分:0)

道歉,它很顺利,但我需要读到这个: https://github.com/phenomnomnominal/angular-2-local-storage/issues/31并将notifyOptions添加到app.module.ts导入

LocalStorageModule.withConfig({
    prefix: 'ng-starter',
    storageType: 'localStorage',
    notifyOptions : {setItem: true, removeItem:true}
}),

答案 1 :(得分:0)

lib中已经存在

localStoragesessionStorage,因此您可以使用localStorage.setItem()和localStorage.getItem()直接使用它。

  

mycomponent.ts

import { Directive, ElementRef, Input } from '@angular/core';
import { UserSettings } from './core/user-settings';
import { LocalStorageService } from 'angular-2-local-storage';

@Directive({
  selector: '[appTheme]'
})
export class AppThemeDirective {
  constructor(el: ElementRef, localStorageService: LocalStorageService) {

    let data = { application: this.application };
    localStorage.setItem('applicationdata', JSON.stringify(data));
    var data = localStorage.getItem('applicationdata');
  }

}

希望这会对你有所帮助。