简体   繁体   中英

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.

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

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM