0

I'm using angular-2-local-storage which has an observable of setItems$ that I'm trying to... Observe, with the following code in a directive:

/** 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);
    });
  }

}

The local storage is updating and persisting well enough in my code, but the updates are not being observed and logging to the console. Any obvious gotcha I missed?

Fewster
  • 100
  • 1
  • 1
  • 10

2 Answers2

0

Apologies, it was going fine but I needed to read this: https://github.com/phenomnomnominal/angular-2-local-storage/issues/31 and add the notifyOptions to the app.module.ts imports

LocalStorageModule.withConfig({
    prefix: 'ng-starter',
    storageType: 'localStorage',
    notifyOptions : {setItem: true, removeItem:true}
}),
Fewster
  • 100
  • 1
  • 1
  • 10
0

localStorage and sessionStorage already there in lib, so you can directly use the same using localStorage.setItem() and 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');
  }

}

Hope this will help you.

Amol Bhor
  • 2,322
  • 1
  • 12
  • 14
  • Hi - I had no problem with the the get/set method of angular-2-local-storage third party module. Just with subscribing to the Observable that it creates, setItems$. Adding "setItem: true" to the notifyOptions config resolved my issue. – Fewster Jun 01 '17 at 14:37