I have class definition but the object coming from JSON does not keep the methods

Asked

Viewed 65 times

0

I have a problem at the moment I get the JSON from the server and I want to use it as my local class.

//classes

export class Pessoa {
 id: number;
 nome: string;
 raca: Raca;

 constructor(){}

 getTeste1(): string {
   return this.id + ' - ' + this.nome;
 }

}

export class Raca {
 id: number;
 nome: string;

 constructor(){}

 getTeste2(): string {
   return this.id + ' - ' + this.nome;
 }
}

//JSON recebido
{
   "id": 20354,
   "nome": "CRISOSTOMO KOLLING",
   "raca":    {
      "nome": "BRANCA",
      "id": 2
   }
}
//recebimento do servidor
let pessoa: Pessoa;

buscar(nome: string){
 this.rest.get(nome).subscribe((v: Pessoa) => {Object.assign(this.pessoa, v)})
}

I was hoping to be able to use this.pessoa.raca.getTeste2() just like I do in java. But I can’t do it. This.pessoa is PESSOA type, but this.personal.raca is NOT RACA type, but Object.

How do I get the JSON return to fill the typing I’ve determined with the classes? Or I can’t create methods inside the files where I create class typing?

  • Try doing with the new and passing the parameters to the constructor. type this.person= new Person(v)

1 answer

0

Try this way:

export class Pessoa {
  id: number;
  nome: string;
  raca: Raca;

  constructor(data?){
    this.id = data.id ? data.id : null;
    this.nome = data.nome ? data.nome : null;
    this.raca = data.raca ? new Raca(data.raca) : null;
  }

  getTeste1(): string {
    return this.id + ' - ' + this.nome;
  }

}

export class Raca {
  id: number;
  nome: string;

  constructor(data?){
    this.id = data.id ? data.id : null;
    this.nome = data.nome ? data.nome : null;
  }

  getTeste2(): string {
    return this.id + ' - ' + this.nome;
  }
}

buscar(nome: string){
  this.rest.get(nome).subscribe( result => {
    if(result){
      this.pessoa = new Pessoa(result)
    }
  }
}
  • It worked !! Just had to adapt. In the builder I had to put one If before the assignments within the constructor, because the angular does not find the attributes. And I had to initialize the attributes with null in its own definition: export class Pessoa {
 id: number = null;
 nome: string = null;
 raca: Raca = null;

 constructor(data?){
 if (data){
 this.id = data.id ? data.id : null;
 this.nome = data.nome ? data.nome : null;
 this.raca = data.raca ? new Raca(data.raca) : null;
 }
 }
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.