【发布时间】:2018-02-01 17:54:51
【问题描述】:
我有一个具有默认值的模型类
export class Person {
_index : string ="hello";
_type : string;
_id : string;
_score : number;
_source : Source = new Source();
}
export class Source {
name : string;
age : number = 0;
salary : number;
details : Details = new Details();
}
export class Details{
year : number = 1997;
education : Education = new Education;
}
export class Education{
score:number = 98;
}
当我创建实例per : Person = new Person (); 时,这会构建一个对象。
{
"_index":"hello",
"_source":{
"age":0,
"details":{
"year":1997,
"education":{
"score":98
}
}
}
现在我已经从模型中的服务器获得了 JSON 模型
}
"_index":"person",
"_type":"single",
"_id":"AWCoCbZwiyu3OzMFZ_P9",
"_version":2,
"found":true,
"_source":{
"name":"sauravss",
"age":"21",
"salary":"50000"
}
}
我想将值填充到我的类对象,但是当我用结果订阅我的类对象时,它会将我的类对象更改为 JSON 对象的形式并消除默认值,从而为我提供从服务器接收到的模型上面的 JSON。订阅后,我会在per 收到此表格。
我想要的是 JSON 对象必须用它匹配的字段填充类 Object 并且不匹配的字段必须包含默认值。
editPerson():void {
const id : string = this.route.snapshot.paramMap.get('id');
console.log(id);
this.personService.getPerson(id).subscribe(person => {
this.per = person;
});
}
getPerson (id : string): Observable<Person> {
const url = `${this.url}/${id}`;
console.log(id);
return this.http.get<Person>(url);
}
【问题讨论】:
-
get<Person>不进行任何转换或转换,它只是一个断言。如果要将 JSON 生成的对象转换为特定的类,明确地这样做。 -
感谢@jonrsharpe 解决了!!
标签: json angular typescript