Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a model class with default values

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;
}

This builds up an object when I create an instance per : Person = new Person ();.

{
"_index":"hello",
"_source":{
"age":0,
"details":{
"year":1997,
"education":{
"score":98
}
}
}

Now I have got JSON Model from server in the model

}
"_index":"person",
"_type":"single",
"_id":"AWCoCbZwiyu3OzMFZ_P9",
"_version":2,
"found":true,
"_source":{
"name":"sauravss",
"age":"21",
"salary":"50000"
}
}

I want to fill the values to my class object but when I subscribe my class object with the result, it changes my class object to the form of JSON object and eliminating the default values giving me the Model that I received from server as the just above JSON. I get this form in per after I subscribe.

What I want is the JSON object must fill the class Object with the fields it matches and the unmatched fields must contain the default values.

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);
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to explicitely convert your Json object to the class you need.

You can do it in constructor:

export class Person() {
    // ...
    constructor(jsonString: string) {
        const jsonData = JSON.parse(jsonString);
        // do your assignment from jsonData
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...