Angular 7 - Popular object on return of API service. httpClient

Asked

Viewed 2,324 times

0

Thanks in advance for your attention.

I am having difficulty popular an object list returned from an API in Angular 7. My service class is returning the service data, but I can’t get popular in my object list (returned from service). Below are details of my implementation.

Json

{  
   "sucess":true,
   "message":"Sucesso",
   "data":[  
      {  
         "codigoPlanoContratacao":"DGC1",
         "codigoCobertura":223,
         "descricaoCobertura":"ASSISTENCIA DOMICILIAR II",
         "codigoTipoRisco":0,
         "valorImportanciaSegurada":0,
         "valorPremioLiquido":24.0
      },
      {  
         "codigoPlanoContratacao":"DGC1",
         "codigoCobertura":400,
         "descricaoCobertura":"INC./RAIO/EXPL./QUEDA AERONAVE",
         "codigoTipoRisco":0,
         "valorImportanciaSegurada":50000,
         "valorPremioLiquido":26.25
      },
      {  
         "codigoPlanoContratacao":"DGC1",
         "codigoCobertura":404,
         "descricaoCobertura":"VENDAVAL/IMPACTO VEICULO",
         "codigoTipoRisco":0,
         "valorImportanciaSegurada":10000,
         "valorPremioLiquido":31.09
      }]
}

My service.ts

  TodasCoberturas() : Coberturas[] {
         this.http.get<Coberturas[]>(this.UrlServiceV1 + "combinadoPlano?codigoTipoRisco=1")   
        .subscribe(
          data => {
            debugger;
            this.coberturas = data;
        });

    return this.coberturas;
}

Class Coverage

export class Coberturas{
    codigoPlanoContratacao: string
    codigoCobertura: number
    descricaoCobertura: string
    codigoTipoRisco: number
    valorImportanciaSegurada: number
    valorPremioLiquido: number
}

componenet.ts

  public coberturas: Coberturas[];

  constructor(public coberturasServices: CoberturasServices) { 
    this.coberturas = this.coberturasServices.retornarListaDetalhe();
    }

html

inserir a descrição da imagem aqui

But in Debugger, I can see my object list, however I can’t get popular in my variable. I tried adding objects in the returned data and I did not succeed, as it informs that my variable is Undefined.

inserir a descrição da imagem aqui

Thank you again.

  • this.covers = date.date;

  • @Marconi, data.data is not recognized. Below link of the image http://prntscr.com/lqnkrd

  • Bruno, console.log(data) what appears?

  • @Marconi, using the console.log as shown below, I have the service data in Browse Browser http://prntscr.com/lqov4m Code http://prntscr.com/lqovw5

  • I have an example here at Github when I was studying angular, take a look at the link I left.

  • One of the examples, in service: ListarPessoa(): Observable<Pessoa[]> {&#xA; return this._http.get<Pessoa[]>(${Api_pessoa}/Pessoa);&#xA; }. In the component this.servico.ListarPessoa()&#xA; .subscribe(resposta => this.pessoa = resposta)

  • @Marconi will take a look at the code. However I have tried several examples on the net and can not popular the list of my service in my object Covers[].

  • Bruno, if I’m wrong you have to use Observable, I just can’t remember why, but I know you have.

  • @Marconi the link that Voce passed, had already made this implementation before and the problem persisted. After the cursor goes through my object, it still remains undefined.

  • Guys, I’ve tried every solution I’ve found on the net and I can’t fix it. Someone can help me with something. Thank you!

  • Bruno will give you one last suggestion: .subscribe((data) => { this.pessoa = data['data']}); I got it from the documentation of angular

  • A question you have some error in the console? has used safe navigation operator(?)?

  • I believe your request is fine, the problem is in its component app-gridCobertudas

  • @Marconi, I have no mistake on the console. The operator (?), I am not using my object Covers, as I told you earlier is not being loaded.

  • @Marconi, I will create a new project with just the default page and see if I can play the dice on the screen. I’ll let you know after the test. Thanks for your attention.

  • Bruno, I remembered you had a project here at stackblitz, in the address zip code field I have a request for viaCep that can be seen on app.service.endereco.ts method GetEndereco. In the endereco.component.ts I call the method, take a look maybe help you!

  • @Marconi, thank you. I’ll analyze.

Show 12 more comments

4 answers

0

Instead of returning the value return an observable in your service:

TodasCoberturas(): Observable<Coberturas[]> {
  return this.http.get<Coberturas[]>(this.UrlServiceV1 + "combinadoPlano?codigoTipoRisco=1")
    .pipe(map(response => response.data));
}

Change the value type of the cover attribute to Observable in its component:

public coberturas$: Observable<Coberturas[]>;

  constructor(public coberturasServices: CoberturasServices) { 
    this.coberturas$ = this.coberturasServices.retornarListaDetalhe();
    }

Use async pipe in your template. That way the angle will subscribe and unsubscribe automatically.

<ng-container *ngIf="coberturas$ | async as coberturas">
  <!-- o seu codigo aqui -->
  <div *ngFor="let cobLinhas of coberturas">... </div>
</ng-container>

0

The list in json is inside an object, so you cannot map that json directly to the Covers array[].

First you create the following class

export class RootObject {
    sucess: boolean;
    message: string;
    data: Coberturas[];
}

Then change the request to

private pedeListaDetalhe() {
        this.http.get<RootObject>(this.UrlServiceV1 + "combinadoPlano?codigoTipoRisco=1")   
        .subscribe(result => {
            this.coberturas = result.data;
        });
    }

A practical example of this working is the following:

@Component({
    template: `
        <div *ngFor="let cobertura of coberturas">
            <!-- coloca o resto do html aqui -->
        </div>
    `
})
export class CoberturasComponent implements OnInit {

    coberturas: Coberturas[];

    ngOnInit(): void {
        this.pedeListaDetalhe();
    }

    private pedeListaDetalhe() {
        this.http.get<RootObject>(this.UrlServiceV1 + "combinadoPlano?codigoTipoRisco=1")   
        .subscribe(result => {
            this.coberturas = result.data;
        });
    }
}
  • The way you created your object does not need the date in the result.

  • Antonio, I made the changes that Voce reported, but still can not assign the list in my object with the data returned from service. Continues as Undefined.

  • @Brunoleite Check my update

  • @António, I performed the update in the code as solitado, but still can not popular my object. Follow image and thanks from now on for the support. http://prntscr.com/lqp8sd

  • @Brunoleite Can you show . ts and . html from the app-gridcoberturas ? In debug, this.coberturas holds data?

  • Antonio, following image as requested. Thanks for your attention. https://i.stack.Imgur.com/Ooaha.png

Show 1 more comment

0

You can try something like this by changing it to this:

in service

todasCoberturas() : Coberturas[] {
       return this.http.get<PayloadCobertura>(\`${this.UrlServiceV1}combinadoPlano? 
                       codigoTipoRisco=1`).pipe(map(res => res.data));
    }

interface

export interface Coberturas{
    codigoPlanoContratacao: string
    codigoCobertura: number
    descricaoCobertura: string
    codigoTipoRisco: number
    valorImportanciaSegurada: number
    valorPremioLiquido: number
}

export interface PayloadCobertura {
  sucess: boolean;
  message: string;
  data: Coberturas[];
}

on the Component

private pedeListaDetalhe() {
  this.yourService.todasCoberturas.subscribe(res => {
    this.coberturas = res;
  });
}

0

Thank you for all the answers, however I only manage using another method to popular my empty object.

What I can’t understand, why I can’t popular my object within the subscribe, because every time I leave within the subscribe, my "item" object becomes empty. During some testing, this was the solution that worked.

  //#region Consultar Combinado de Planos
    ConsultarItem(){
      this.limparItens();
      this.service.consultarItem(this.codItem)
      .subscribe(
                result  => {
                this.item = result.data;
                this.processarDados(this.Item)
            });
    }

     //Popular objeto rtornado do services 
     processarDados(item: Item[]){
      this.Item = item;
    }
    //#endregion 

Browser other questions tagged

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