【问题标题】:How to call the data from arrays in angular 6如何在角度 6 中调用数组中的数据
【发布时间】:2019-07-02 08:12:40
【问题描述】:

当我登录时,我收到如下响应。我想将令牌和 ID 存储在本地存储和 cookie 中。我怎么能在 angular6 中调用数据

{
    code: 200
    data:
    {
       alt_email: null
       balance: "100.00"
       current_institution_id: null
       designation: null
       id: 75
       token: "5c5d0d8cb6716"
    }
    status:true
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    试试这个简单 -

    let a = {
            code: 200,
            data: {
                alt_email: null,
                balance: "100.00",
                current_institution_id: null,
                designation: null,
                id: 75,
                token: "5c5d0d8cb6716",
            },
            status: true
        };
    
    localStorage.setItem('token', a.data.token);
    localStorage.setItem('id', a.data.id);
    

    PS : 如果 cookie 数据总是使用 document.cookie 之类的语法保存在名称-值对中。

    更多详情请阅读这里基本解释here

    【讨论】:

      【解决方案2】:

      如果你的响应对象是这样的

       let res =    {
              code: 200
              data: {
              alt_email: null
              balance: "100.00"
              current_institution_id: null
              designation: null
              id: 75
              token: "5c5d0d8cb6716"
              }
              status:true
          }
      

      那么你可以使用

      localStorage.setItem('id', res.data.id);
      localStorage.setItem('token', res.data.token);
      

      你可以在任何地方使用

      localStorage.getItem('id');
      localStorage.getItem('token');
      

      【讨论】:

      • “字符串”类型上不存在属性“数据”之类的抛出错误
      【解决方案3】:

      我假设您将其作为订阅登录服务的 Observable 中的响应,因为您提到了 Angular 6

      this.someService.login().subscribe(res => {
        localStorage.setItem('token', res.data.token); // <-- add these lines
        localStorage.setItem('id', res.data.id);  // <-- 
      });
      

      对于 cookie,请使用此处描述的包或服务How to create cookies in Angular 6?

      【讨论】:

      • 我终于明白了
      • 很高兴我能帮助@malar
      • 请考虑对有帮助的解决方案进行投票/选择答案。
      • 我得到的结果是编译错误,例如错误 TS2339:类型“Store[]”上不存在属性“数据”。
      猜你喜欢
      • 2019-01-21
      • 1970-01-01
      • 2019-02-01
      • 2022-10-24
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      相关资源
      最近更新 更多