1

I'm getting some JSON object stored from HTML5 local storage and assign it to an object.

this.currentWebUser = Object.assign({}, JSON.parse(localStorage.getItem("currentUser")));

currentWebUser is an object of class my class WebUser

export class WebUser {
  private _id: number;
  private _connectionID: number;

  public set id(value: number) {
    this._id = value;
  }

  public get id(): number {
    return this._id;
  }

  public set connectionID(value: number) {
    this._connectionID = value;
  }

  public get connectionID(): number {
    return this._connectionID;
  }
}   

When I try to get the value of id by using this.currentWebUser.id (In typescript this refer getter method of id) I'm getting undefined value, not the actual value.

enter image description here

But in chrome console, I can see the actual value is there.

enter image description here

Need help, Thanks in advance !!!

Nibras
  • 329
  • 1
  • 6
  • 23
  • 1
    Its supposed to show like that. You are getting undefined in your editor because you haven't defined and initialized the object. But as soon as you run it in browser, it fetches the data from local storage and the structure becomes known. – MonkeyScript Oct 25 '19 at 04:59
  • 1
    _connectionID is not connectionID – noririco Oct 25 '19 at 05:27
  • @noririco _connectionID is private attribute of the class. As mentioned in the question, this.currentWebUser.connectionID means acess the _connectionID value via get connectionID method – Nibras Oct 25 '19 at 05:33
  • 1
    assign value to currentWebUser in constructor itself. – varundhariyal Oct 25 '19 at 05:34

1 Answers1

2

The problem is that the value returned by

Object.assign({}, JSON.parse(localStorage.getItem("currentUser")));

is not an instance of your WebUser class. It is an Object with the fields that were present in the Json (which is clearly visible in your debugger screenshot).

You can check currentWebUser.__proto__.constructor to see that it points to Object(), not WebUser()

You are able to assign the result of Object.assign to currentWebUser variable because return type of Object.assign is any.

You need to make sure that you deserialise to the instance of your class. There are a few ways to do it, see the following links

let webUser = Object.assign({}, JSON.parse('{"_connectionID": 1, "_id":2}'));
let webUser2 = Object.assign(
  new WebUser(),
  JSON.parse('{"_connectionID": 1, "_id":2}')
);
console.log(webUser);
console.log(webUser2);

Output:

{_connectionID: 1, _id: 2}          // Your code
WebUser {_connectionID: 1, _id: 2}  // What you expect
Lesiak
  • 22,088
  • 2
  • 41
  • 65