Собственный toJSON помещает объект object в локальное хранилище - PullRequest
0 голосов
/ 11 мая 2019

Мне нужен вошедший в систему пользователь, и чтобы получать его даже после обновлений, я помещаю его значения в локальное хранилище. Когда я использую JSON.stringify (), он помещает правильные значения в локальное хранилище, но с _ перед именами ключей, и я не знаю почему (я назвал свои личные свойства _id, например, но я написал геттеры и думаю, что Должны ли они называть их снова нормально, верно?). Поскольку это не сработало, я написал собственный метод toJSON:

toJSON(): any {
    return {
      id: this._id,
      firstName: this._firstName,
      lastName: this._lastName,
      email: this._email,
      phoneNumber: this._phone,
      country: this._country,
      comments: this._comments.map(c => c.toJSON)
    };

но когда я вызываю его, он помещает [объект Object] в локальное хранилище, и я не могу понять, почему он это сделал.

Мне нужно либо сделать так, чтобы JSON.stringify поместил мой атрибут в localStorage, либо мне нужно исправить мой toJson.

Модель пользователя:

import { Comment } from '../image/comment.model';

export class User {
  constructor(
    private _id: number,
    private _firstName: string,
    private _lastName: string,
    private _email: string,
    private _phone: string,
    private _country: string,
    private _comments: Comment[]
  ) {}

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

  get firstName(): string {
    return this._firstName;
  }

  get lastName(): string {
    return this._lastName;
  }

  get email(): string {
    return this._email;
  }

  get phone(): string {
    return this._phone;
  }

  get country(): string {
    return this._country;
  }

  get comments(): Comment[] {
    return this._comments;
  }

  static fromJSON(json: any): User {
    return new User(
      json.id,
      json.firstName,
      json.lastName,
      json.email,
      json.phoneNumber,
      json.country,
      json.comments
    );
  }

  toJSON(): any {
    return {
      id: this._id,
      firstName: this._firstName,
      lastName: this._lastName,
      email: this._email,
      phoneNumber: this._phone,
      country: this._country,
      comments: this._comments.map(c => c.toJSON)
    };
  }
}

служба аутентификации

this.getUser(email).subscribe(usr => { //this gets my user via its email from the backend
              localStorage.setItem('visitor', usr.toJSON());
              this._loggedInUser$.next(usr);
            });

this._loggedInUser$ = new BehaviorSubject<User>(
      localStorage.getItem('visitor')
        ? User.fromJSON(localStorage.getItem('visitor'))
        : null
    );

  get loggedInUser$(): BehaviorSubject<User> {
    return this._loggedInUser$;
  }

Комментарий

export class Comment {
  private _id: number;
  constructor(
    private _author: string,
    private _content: string,
    private _date: Date,
    private _imageId: number,
    private _visitorId: number
  ) {}

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

  get author(): string {
    return this._author;
  }

  get content() {
    return this._content;
  }

  get date(): Date {
    return this._date;
  }

  get imageId(): number {
    return this._imageId;
  }

  get visitorId(): number {
    return this._visitorId;
  }

  static fromJSON(json: any): Comment {
    let comment = new Comment(
      json.author,
      json.content,
      json.date,
      json.myImageId,
      json.visitorId
    );
    comment.id = json.id;
    return comment;
  }

  toJSON(): any {
    return {
      id: this._id,
      author: this._author,
      content: this._content,
      date: this._date,
      myImageId: this._imageId,
      visitorId: this._visitorId
    };
  }
}

Если вам понадобится больше кода, просто дайте мне знать!

1 Ответ

0 голосов
/ 12 мая 2019

Это может быть потому, что вы дали переменным то же имя, что и имена свойств объекта JSON. Если вы хотите избавиться от подчеркивания, попробуйте указать переменные с разными именами.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...