javascript - TypeError:无法读取 es6 模型上未定义的属性“first_name”
问题描述
我想在 es6 模型中设置 JSON API,但出现此错误 TypeError: Cannot read property 'first_name' of undefined
JSON API:
{ “类型”:“用户”, “身份证”:2, “属性”: { “用户名”:“madelynn81”, “电子邮件”:“taylor63@mills.biz”, "first_name": "埃米尔", "last_name": "Veum", “created_at”:“2018-11-17 11:48:13” }, “链接”:{ “自我”:“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
}
}
我该如何解决
解决方案
从您的问题中不清楚您如何使用吸气剂来获取价值。一个问题:您的 set/get 对应使用相同的属性名称命名。它们的命名应与持有该值的属性不同。例如:_id
用于值属性名称,以及id
用于获取/设置名称。
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)
推荐阅读
- ios - 如何使用图像发送通知 - react-native-firebase
- php - 如何为任何字符和空格制作正则表达式
- php - 如何修复godaddy服务器上codeigniter网站的“错误连接超时错误”?
- php - 仅在用户登录时打开页面/帖子/产品 - WordPress
- javascript - 改进 javascript 动画以使其流畅和优化
- blockchain - 集成区块链支付网关
- twitter - Twitter 搜索所有以...结尾的词(语料库语言学)
- sql - 如何选择连接?右或左
- node.js - npm 命令提示符安装
- php - Phalcon choose version to install