admin管理员组

文章数量:1331849

I m still new with Typescript, i want to output only username from this localStorage:

localStorage.getItem('currentUser')

which currently outputing: {"username":"root","password":"root"}

How can i do it ?

I m still new with Typescript, i want to output only username from this localStorage:

localStorage.getItem('currentUser')

which currently outputing: {"username":"root","password":"root"}

How can i do it ?

Share Improve this question edited Apr 12, 2018 at 3:49 ecraig12345 2,4572 gold badges20 silver badges27 bronze badges asked Apr 12, 2018 at 1:13 M1rwenM1rwen 1,9325 gold badges17 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Short answer: Convert the string back to an object using JSON.parse:

var user = JSON.parse(localStorage.getItem('currentUser'));
console.log(user.username);

(Note: this applies to JavaScript in general, not just TypeScript)


Details

Items are stored in localStorage as strings. So to save an object in localStorage, you convert it to a string using JSON.stringify(obj). (Whoever saved your user object to localStorage likely used this method.)

To convert back to an object, use JSON.parse(str). Note that this can throw an exception if the string isn't a valid JSON representation of an object.

Example of all that with your user object (it's also valid JavaScript if you remove type declarations):

interface IUser {
  username: string;
  password: string; // please don't do this in real code
}

function saveCurrentUser(user: IUser): void {
  localStorage.setItem('currentUser', JSON.stringify(user));
}

function getCurrentUser(): IUser {
  var userStr = localStorage.getItem('currentUser');
  try {
    return JSON.parse(userStr);
  } catch (ex) {
    return null; // or do some other error handling
  }
}

var user = { username: 'root', password: 'root' };
saveCurrentUser(user);

// elsewhere...
var savedUser = getCurrentUser();
if (savedUser) {
  console.log('Current user: ' + savedUser.username);
} else {
  console.log('Current user not found');
}

You need to convert the JSON string back to an Object with JSON.parse

var user = JSON.parse(localStorage.getItem('currentUser'));

and then you can access the username field in it

if(user){
   console.log(user.username);
}

I use this technique: Apply JSON encoding via Proxy, cast this Proxy to an object that represents your LocalStorage Schema:

export let ls = new Proxy(localStorage, {
    get(o, prop) { return JSON.parse(o.getItem(prop as string) || "") },
    set(o, prop, value, _) { o.setItem(prop as string, JSON.stringify(value)); return true; }
}) as unknown as StorageT;

type Settings = { // just an example for a structured type
    a: string
    b: number
}

type StorageT = { // your type of Localstorage
    showside: boolean;
    usercount: number;
    settings: Settings;
}

// usage:

import { ls } from ...

ls.showside = !ls.showside
ls.usercount++
...

本文标签: Extract username from localStorage TypescriptJavaScriptStack Overflow