gpt4 book ai didi

angularjs - 如何从 Angular2 本地存储中保存和检索数据?

转载 作者:太空狗 更新时间:2023-10-29 17:08:51 24 4
gpt4 key购买 nike

我能够在浏览器的 localstorage 中存储一个授权 token ,但我无法将其作为字符串检索。我找不到有关如何执行此操作的任何示例。

最佳答案

您可以自己编写一个服务来封装序列化和反序列化:

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

bootstrap 调用中将其添加到您的提供者:

bootstrap(App, [ ..., StorageService]);

或者在你的根组件中:

@Component({
// ...
providers: [ ..., StorageService]
})
export class App {
// ...
}

然后在你需要的组件中,在构造函数中注入(inject)即可:

export class SomeComponent {
private someToken: string;

constructor(private storageService: StorageService) {
someToken = this.storageService.read<string>('my-token');
}

// ...
}

关于angularjs - 如何从 Angular2 本地存储中保存和检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38055869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com