Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: JSON to Class Object in Angular

saurav sarkar:

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 {
const url = `${this.url}/${id}`;
console.log(id);
return this.http.get(url);
}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: JSON to Class Object in Angular

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×