Angular 7: Biding an object that will receive a json from an HTTP GET

Asked

Viewed 162 times

0

Let’s say I have the typed object:

x: Endereco

public interface Endereco {
  rua: string;
  numero: number;
}

And I have an http GET that will feed this variable x. The problem is that in the request I get a json with the "neighborhood" parameter that I don’t want to go to my variable x. How do I 'filter' it?

{
  rua: "nome da rua",
  numero: 34,
  bairro: "Não quero isso"
}

Actually, I do it that way:

http.get<Endereco>('url')
   .subscribe(resposta => this.x = resposta)

Here the variable X turns into an object with the neighborhood parameter, and I don’t want that to happen.

  • http.get<Endereco>('url')&#xA; .subscribe(resposta => { this.x.rua = resposta['rua'] this.x.numero = resposta['rua'] })try like this

  • The problem of setting manually is that I can have an object with 20 or more parameters. Do I have to set them all manually? I don’t understand how typescript can force a typed object to a parameter that is not in it.

  • John, you do not need to have all the properties of your object equal to those that come from the answer. the only thing that will happen is that if object will extend.

  • But I don’t want it to extend, I just want the properties I defined in it. I think there should be a method to doing this without me having to set the properties one by one. I work with a giant bank, so it turns out to be a nuisance, but thanks for the help.

1 answer

1


You have to map your api response template to your application’s internal state model, for this the best is to use the map operator:

http.get<Endereco>('url')
    .pipe(
         map(resposta=>{
            return {
               resposta.rua,
               resposta.numero
            }
        })
     )
   .subscribe(resposta => this.x = resposta)

Browser other questions tagged

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