我使用HttpClient从API中获取Json,并使用该HttpClient的autoMapping将json映射到目标对象,如下所示:
this.httpClient.post<Person>(url, body, { headers: headers, params: httpParams }).retry(ConfigurationService.apiHttpRetries)我的问题是我的Person类包含如下所示的getter:
get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }在httpClient.Post之后,我将得到一个Person对象,它只包含从json返回的字段,而不包含其他属性,并且不包含FullName getter。
我试着用Object.Assign,但它也不起作用.
如果httpClient.post泛型方法不执行映射而只执行返回JSON.parse(jsonResult)之类的操作,那么它有什么大不了的呢?
发布于 2018-03-27 16:06:52
类构造函数中的Object.assign():
class Person {
firstName: string;
lastName: string;;
constructor(data: Object|Person) {
Object.assign(this,data);
}
get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }
}
...
this.httpClient.post<Person>(url, body, headers).pipe(
retry(ConfigurationService.apiHttpRetries),
map(personProperties => new Person(personProperties),
);不需要映射您自己的每个属性:
this.firstName = firstName;
this.lastName = lastName;发布于 2018-03-27 15:35:29
泛型参数仅用于编译时的键入。您正在通知其余代码,从响应返回的对象将与Person兼容。如果响应不包括firstName或lastName属性,除非您自己检查对象形状,否则代码仍然无法正常工作。如果希望该对象具有方法或其他getter,则必须亲自实例化它。
interface PersonResponse {
firstName: string;
lastName: string;
}
this.httpClient.post<Person>(url, body, headers).pipe(
retry(ConfigurationService.apiHttpRetries),
map(personProperties => new Person(personProperties),
);所以你可以
class Person {
constructor({ firstName, lastName }) {
this.firstName = firstName;
this.lastName = lastName;
}
get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }
}https://stackoverflow.com/questions/49516876
复制相似问题