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

拉吉·库玛(Raj Kumar)

我可以将auth令牌存储在浏览器的中localstorage,但无法将其作为字符串检索。我找不到任何有关如何执行此操作的示例。

rinukkusu

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

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 {
    // ...
}

然后在需要的组件中,将其注入构造函数中:

export class SomeComponent {
    private someToken: string;

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

    // ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章