0

When I cast to Class Object extra values from Json pop up when I Log the Class object.

This is the Class Model

export class PersonModel {
    _index : string;
    _type : string;
    _id : string;
    demo : "test";
    _score : number;
    _source : {
        name : string;
        age : number;
        salary:number;
        details :{
            year: number;
            education:{
                score:number;
            };
        };
    };
}

This is final output I get when I print the class object.Its not even printing the demo field from class.

{
"_index":"person",
"_type":"single",
"_id":"AV-Migit0bfajafmy3",
"_version":2,
"found":true,
"_source":{
"name":"hyd",
"salary":600000,
"age":27
}

I wanted to know how to convert the Json into Class Object so that I can fill the details field and save it to database.

Here is the conversion code

getPerson (id : string): Observable<PersonModel> {
    
    const url = `${this.url}/${id}`;
    return this.http.get< PersonModel >(url);  
  }
Arashsoft
  • 2,749
  • 5
  • 35
  • 58
saurav sarkar
  • 187
  • 1
  • 8

3 Answers3

1

You should actually create separate classes for your source and details, import them and refer inside the PersonModel class

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I have done according to it but facing an other issue . Can you have a look on it https://stackoverflow.com/questions/48557743/json-to-class-object-angular-4 – saurav sarkar Feb 01 '18 at 08:16
0

This code does not create an instance of your class and populate it. Rather, it creates a JSON object that resembles the class using the data provided in the Http response.

getPerson (id : string): Observable<PersonModel> {
    
    const url = `${this.url}/${id}`;
    return this.http.get< PersonModel >(url);  
  }

If you want an instance of your class (so you can populate any other properties or call its methods), you need to create the instance and copy the JSON object into it.

Something like this in the calling component's subscribe():

const myPerson = Object.assign(new PersonModel(), <dataFromHttp>)
DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • I have done as suggested but facing an other issue . Can you have a look on it https://stackoverflow.com/questions/48557743/json-to-class-object-angular-4 – saurav sarkar Feb 01 '18 at 08:17
0

You have a problem with the type of demo, it should be demo:string

export class PersonModel {
    _index : string;
    _type : string;
    _id : string;
    demo : string;
    _score : number;
    _source : {
        name : string;
        age : number;
        salary : number;
        details : {
            year: number;
            education : {
                score : number;
            };
        };
    };
}
Jorge Tovar
  • 1,374
  • 12
  • 17