【发布时间】:2018-11-19 21:45:45
【问题描述】:
在我下面的代码中,
- 我在我的 Person 类中调用静态“findAllPeople”方法。此方法返回一组 Person 对象。
- Person 类还有一个用于 fullName 的 getter。
问题:
res.json(Array.from(people))返回 Person 对象的数组,但没有 fullName 属性。
当我在 VS Code 中调试 Array.from(people) 时,它会正确返回带有 fullName 属性的 Person 对象数组。但是当我评估JSON.stringify(Array.from(people)) 时,我得到一个没有getter 属性的字符串。
我已经尝试过使用[...people] 而不是Array.from(people)。但同样的结果。
所以是 stringify 动作导致了这个问题(我假设......)。
我怎样才能创建一个返回带有 fullName 属性的数组的响应(基于 fullName getter)?
controller.js
const Person = require('./Person');
exports.getAll = function(req, res, next) {
Person.findAllPeople()
.then((people) => {
res.json(Array.from(people));
})
.catch((err) => {return next(err);});
}
Person.js
class Person {
constructor(personId, first, last, email, birthday) {
this._id = personId ? personId : undefined;
this.firstName = first ? first : undefined;
this.lastName = last ? last : undefined;
this.email = email ? email : undefined;
this.birthday = birthday ? new Date(birthday) : undefined;
this.relations = new Map();
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
static findAllPeople() {
return personRepository.getAll("ONLY_NAMES")
.then((people) => {
people.forEach((person) => {
if (person.relations.size === 0) {
person.relations = undefined;
}
})
return people;
})
.catch(console.error);
}
}
module.exports = Person;
【问题讨论】: