saurav sarkar
saurav sarkar

Reputation: 217

Angular 4 Json object to Class Object

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

Upvotes: 0

Views: 663

Answers (3)

Jorge Tovar
Jorge Tovar

Reputation: 1869

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

Upvotes: 0

DeborahK
DeborahK

Reputation: 60528

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>)

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

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

Upvotes: 1

Related Questions