typescript 如何从 Angular2 本地存储中保存和检索数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38055869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to save and retrieve data from Angular2 local storage?
提问by Raj Kumar
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.
我能够在浏览器的 中存储一个身份验证令牌localstorage
,但我无法将其作为字符串检索。我找不到任何关于如何做到这一点的例子。
回答by rinukkusu
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
调用中将其添加到您的提供者:
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');
}
// ...
}