【问题标题】:ionic 3 - storage.get function return null value outside the function [duplicate]ionic 3-storage.get函数在函数外返回空值[重复]
【发布时间】:2018-09-13 14:37:25
【问题描述】:

存储。获取函数在函数之外返回空值。 这是我的代码

username:any;

this.storage.get('user').then((value) => {
       this.username = value;
    });

console.log(this.username);

output : undefined;

【问题讨论】:

  • 请注意this.storage代码?
  • 什么意思请解释一下?
  • 我的意思是你的this.storage 定义在哪里?你是说本地存储吗?
  • 你是否设置了用户的数据......
  • this.storage.set('user',detail);是的,我已经在用户中设置了数据

标签: angular typescript ionic3


【解决方案1】:

如果你想使用本地存储:

username:any;

this.username = localStorage.getItem('user');

console.log(this.username);

【讨论】:

    【解决方案2】:

    你为什么使用函数? 您可以使用以下代码简单地获取存储值:

    this.username = JSON.parse(localStorage.getItem('user'));
    

    【讨论】:

    • 我想存储数组但它提供字符串
    • JSON.parse 将字符串转换为数组。
    • 这是我的数组 { "user_type": "shipper", "name": "testuser", "mobile_number": "1234567890", "updated_at": "2018-04-04 06:57 :42", "created_at": "2018-04-04 06:57:42", "id": 40 } localStorage.setItem('user', auth);首先,我设置了项目,但是当我得到结果时,这向我显示错误“JSON.parse:JSON 数据的第 1 行第 2 列的意外字符”这是我的 getItem this.username = JSON.parse 代码(localStorage.getItem('user'));
    • localStorage.setItem('user', JSON.stringify(auth)); 将身份验证数据保存为字符串而不是对象。
    • 它的工作......非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多