如何将JSON数组存储到本地存储

时间:2020-09-21 18:51:09

标签: javascript angular typescript angular8

{
    "Id": 1,
    "Fullname": "test name",
    "Username": "test",
    "Password": "$2a$10$f.upx2WTxlriul4QK/1GSuCxd6Dmw7.NgVeJ2VfuiC0uIZai5rsD6",
    "PasswordSalt": "$2a$10$uCpbT0wAGFx5NxCwlZOkK.",
    "Enabled": true,
    "Locked": false,
    "Deleted": false,
    "LogonAttempts": 0,
    "LastLogon": null,
    "LastModifiedBy": "Tester",
    "LastModifiedOn": "2020-09-14T16:08:35.853Z",
    "CreatedBy": "Tester",
    "CreatedOn": "2020-09-14T16:08:35.853Z",
    "UserRoles": [
        {
            "Id": 3,
            "Roles": "Admin",
            "RolePermissions": [
                {
                    "Id": 1,
                    "Permission": "Administrator"
                },
                {
                    "Id": 2,
                    "Permission": "Currency"
                }
            ]
        }
    ]
}

我正在尝试保存RolePermisions,然后将每个权限保存到本地存储,但是我不确定如何执行此操作。最好是我想在ngOnInit()里面做

TypeScript

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  constructor( private activatedRoute: ActivatedRoute,) { }
  access_token = null;

  
  ngOnInit() {
    this.access_token = localStorage.getItem('access_token');
  }

}

我希望能够存储access_token以及RolePermision和每个权限

2 个答案:

答案 0 :(得分:1)

您是否只想保存RolePermissions而不是UserRoles,因为用户将只有一个角色?因为如果您要存储多个角色,则应该存储UserRoles。 无论如何,仅存储RolePermissions并假设您始终拥有一个,并且上述对象存储在名为userdata的变量中,即:

localStorage.RolePermissions = JSON.stringify(userdata.UserRoles[0].RolePermissions);

要检索它,您将执行以下操作:

var permissions = JSON.parse(localStorage.RolePermissions);

答案 1 :(得分:0)

存储到localStorage时,需要将数据存储为字符串(因此将权限数据转换为字符串。),并且从localStorage加载数据时,需要将该字符串转换为数组值。