【问题标题】:How to store a array element in local storage如何将数组元素存储在本地存储中
【发布时间】:2019-08-16 16:12:30
【问题描述】:

我是 ionic 3 的新手。我需要在本地存储中存储一个数组元素。

我试过这段代码,但它只存储数组。不是数组元素

这是我的代码:

signin() {
    this.showLoader();
    console.log(this.loginData);
    this.authService.login(this.loginData).then((result) => {
      this.loading.dismiss();
      this.data = result;
      console.log('Result:'+JSON.stringify(result));
      localStorage.setItem('token', JSON.parse(JSON.stringify(this.data))._body.access_token);
       console.log(JSON.parse(JSON.stringify(this.data))._body.access_token);
      this.navCtrl.setRoot(DashboardPage);

这是一个结果值

Result:{"_body":"{\"access_token\":\"J0ErN5qf4btTJaB27FLMNLTrhwBxZMTCBAxc4m25\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"refresh_token\":\"OMVvOXHgsfKwWtHyYwjlzsO5Jxb44H0Oi9lf7Pk6\"}",

简而言之,我需要将 access_token 存储在 本地存储 中。请提出一些方法。

提前致谢

【问题讨论】:

  • 您好,您是否尝试过将“结果”直接存储在本地存储中而不将其转换为 JSON 格式?
  • 是的,我试过了,但显示“token= undefined”
  • 如果你 console.log result._body.access_token 会得到什么?如果您只需要存储访问令牌,您似乎可以从 result 对象中获取该元素,而不会弄乱 parse/stringify?
  • 在您的情况下,什么是“数组元素”?我有点困惑。你的 Result 在我看来是一个 json。

标签: json ionic-framework ionic2 ionic3 local-storage


【解决方案1】:

问题是你如何将值存储在 localStorage 中,正确的实现是:

保存到本地存储:

localStorage.setItem('token', JSON.stringify(this.data._body.access_token));

从 localStorage 获取:

JSON.parse(localStorage.getItem('token'));

【讨论】:

    猜你喜欢
    • 2016-08-21
    • 2014-12-04
    • 2014-01-17
    • 1970-01-01
    • 2015-12-23
    • 2014-05-10
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多