how to save and retrieve data from Angular2 local storage?

Raj Kumar picture Raj Kumar · Jun 27, 2016 · Viewed 11.3k times · Source

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.

Answer

rinukkusu picture rinukkusu · Jun 27, 2016

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

    // ...
}