9

I was able store an auth token in the browser's localstorage, but I wasn't able retrieve it as string. I can't find any examples on how to do that.

Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
Raj Kumar
  • 583
  • 2
  • 5
  • 9
  • Could you paste your code that retrieves the local storage please? – Antonis Zisis Jun 27 '16 at 14:07
  • There's another question addressing this that recommends using a service and Observables, to be able to keep track of changes to localStorage items: http://stackoverflow.com/questions/35397198/how-can-i-watch-for-changes-to-localstorage-in-angular2 – Harry Oct 28 '16 at 16:18

1 Answers1

19

You could write yourself a service to encapsulate the serializing and deserializing:

export class StorageService {
    write(key: string, value: any) {
        if (value) {
            value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
    }

    read<T>(key: string): T {
        let value: string = localStorage.getItem(key);

        if (value && value != "undefined" && value != "null") {
            return <T>JSON.parse(value);
        }

        return null;
    }
}

Add it to your providers either in the bootstrap call:

bootstrap(App, [ ..., StorageService]);

or in your root component:

@Component({
    // ...
    providers: [ ..., StorageService]
})
export class App {
    // ...
}

Then in the component where you need it, just inject it in the constructor:

export class SomeComponent {
    private someToken: string;

    constructor(private storageService: StorageService) {
        someToken = this.storageService.read<string>('my-token');
    }

    // ...
}
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71