Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save and retrieve data from Angular2 local storage?

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.

like image 956
Raj Kumar Avatar asked Jun 27 '16 13:06

Raj Kumar


1 Answers

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

    // ...
}
like image 82
rinukkusu Avatar answered Oct 02 '22 14:10

rinukkusu