Ошибка типа: невозможно прочитать свойство 'first_name' из неопределенного в модели es6 - PullRequest
0 голосов
/ 07 декабря 2018

Я хочу установить JSON API в модели es6, но получаю эту ошибку TypeError: Невозможно прочитать свойство 'first_name' из неопределенного

JSON API:

{
      "type": "user",
      "id": 2,
      "attributes": {
        "username": "madelynn81",
        "email": "taylor63@mills.biz",
        "first_name": "Emile",
        "last_name": "Veum",
        "created_at": "2018-11-17 11:48:13"
      },
      "links": {
        "self": "http://test.test/api/v1/user/2"
      }
    }

es6 модель

class UserModel {
    constructor(data) {
        this.id = data.id;
        this.first_name = data.attributes.first_name;
        this.last_name = data.attributes.last_name;
        this.username = data.attributes.username;
        this.email = data.attributes.email;
        this.created_at = data.attributes.created_at;
        this.link = data.links.self;
    }

    get getId() {
        return this.id;
    }

    set setId(value) {
        this.id = value;
    }

    get getFirstName() {
        return this.first_name;
    }

    set setFirstName(value) {
        this.first_name = value;
    }

    get getLastName() {
        return this.last_name;
    }

    set setLastName(value) {
        this.last_name = value;
    }

    get getUsername() {
        return this.username;
    }

    set setUsername(value) {
        this.username = value;
    }

    get getEmail() {
        return this.email;
    }

    set setEmail(value) {
        this.email = value;
    }

    get getCreatedAt() {
        return this.created_at;
    }

    set setCreatedAt(value) {
        this.created_at = value;
    }

    get getLink() {
        return this.link
    }

    set setLink(value) {
        this.link = value
    }
}

как я могу это исправить

Ответы [ 2 ]

0 голосов
/ 07 декабря 2018

Я не уверен, какие у вас цели, но обычно в javascript используется более простой синтаксис, а объекты очень похожи на массивы.

Вот краткий пример:

    const data = {
      "type": "user",
      "id": 2,
      "attributes": {
        "username": "madelynn81",
        "email": "taylor63@mills.biz",
        "first_name": "Emile",
        "last_name": "Veum",
        "created_at": "2018-11-17 11:48:13"
      },
      "links": {
        "self": "http://test.test/api/v1/user/2"
      }
    }

    const user = { 
      id: data.id,
      firstName: data.attributes.first_name,
      // other props,
    };

    console.log(user.firstName);

Фактически, если вы заметите, ваши данные уже являются объектом.

0 голосов
/ 07 декабря 2018

Из вашего вопроса не ясно, как вы используете геттер для получения значения.Одна проблема: ваши пары set / get должны быть названы с тем же именем свойства.Они должны называться иначе, чем свойство, содержащее значение.Например: _id для имени свойства value и id для имени get / set.

class UserModel {

  constructor(data) {
    this._id = data.id;
    this._firstName = data.attributes.first_name;
  }

  get id() {
    return this.id;
  }

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

  get firstName() {
    return this._firstName;
  }

  set firstName(value) {
    this._firstName = value;
  }

}
const data = {
  "type": "user",
  "id": 2,
  "attributes": {
    "username": "madelynn81",
    "email": "taylor63@mills.biz",
    "first_name": "Emile",
    "last_name": "Veum",
    "created_at": "2018-11-17 11:48:13"
  },
  "links": {
    "self": "http://test.test/api/v1/user/2"
  }
}

const user = new UserModel(data);
console.log(user.firstName)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...