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