2

I have a menu to appear based on being logged. I am using json web tokens in local storage for my authentication, I want to watch for a change to localStorage and then re-update my view on new information.

How can I watch for changes to localstorage?

I set my localStorage with this

localStorage.setItem('jwt', my_token); The things I would like to do is check if I have a token, if I don't nothing happens, but when there is a change fire an event. From what I know I have to create a service, inject it where I want and susbscribe me to the observable.

What I have is the service, I don't know how to watch for the changes.

my service is:

import { Injectable } from 'angular2/core';

@Injectable()
export class LocalStorageService {
    private storage: any;

    constructor() {
        this.storage = localStorage;
    }

    public retrieve(key: string): any {
        var item = this.storage.getItem(key);

        if (item && item !== 'undefined') {
            return JSON.parse(this.storage.getItem(key));
        }

        return;
    }

    public store(key: string, value: any) {
        this.storage.setItem(key, JSON.stringify(value));
    }

}
Diego Unanue
  • 6,576
  • 8
  • 47
  • 67
  • Just curious.. What is `localStorage`? Don't see it being imported or declared anywhere in your snippet. – Chrillewoodz Apr 06 '16 at 12:22
  • You needs to work at a higher abstraction layer. Where ever you are setting the token first time. You should raise an event using `EventEmitter. Other components a subscribe to it and react accordingly – Chandermani Apr 06 '16 at 12:26
  • It's the javascript object to work with the local storage: http://www.w3schools.com/html/html5_webstorage.asp – Diego Unanue Apr 06 '16 at 12:28
  • 2
    I am not familiar with angular but if its possible you can bind event to window in javascript `window.addEventListener('storage', function(e) {}` https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API – Raunak Kathuria Apr 06 '16 at 12:29
  • You mean that you want to implement an observable when some parts of your application call the `store` method of your `LocalStorageService` service? – Thierry Templier Apr 06 '16 at 14:10
  • Yes, I have a login that saves a token in localstorage, when the user is logged I want to show a menu. – Diego Unanue Apr 06 '16 at 14:16

1 Answers1

2

I've created a service that can do this for you if you still haven't found a suitable answer. The h5webstorage already handle watching both localStorage and sessionStorage events and synchronizes the changes. All you have to do is use it like a normal object.

SirDarquan
  • 81
  • 2
  • dude, could you please help me running your code as when i tried running it does not do any. may I need to follow some different steps please check npm start then it shows... [0] 12:51:40 AM - Compilation complete. Watching for file changes. – Narottam Goyal Jun 06 '16 at 19:23