1

Faço o consumo de uma API que me retorna um JSON. O retorno funciona perfeitamente, porém, quando eu tento acessar alguma propriedade desse JSON, ele me da como undefined. Já validei o JSON e está ok

JSON:

    [
  {
      "ratingDate": "2018-12-21",
      "rate1": 0,
      "rate2": 0,
      "rate3": 1,
      "rate4": 0,
      "rate5": 0,
      "detractor": 100,
      "promoter": 0,
      "nps": -100,
      "Reserva": 1,
      "Abertura": 0,
      "Finalizar": 0,
      "VeiculoSujo": 0,
      "Abastecimento": 0,
      "CheiroCigarro": 0,
      "VagaRuim": 1,
      "Outro": 0
  },
  {
      "ratingDate": "2018-12-22",
      "rate1": 1,
      "rate2": 0,
      "rate3": 0,
      "rate4": 0,
      "rate5": 4,
      "detractor": 20,
      "promoter": 80,
      "nps": 60,
      "Reserva": 0,
      "Abertura": 0,
      "Finalizar": 0,
      "VeiculoSujo": 1,
      "Abastecimento": 1,
      "CheiroCigarro": 1,
      "VagaRuim": 0,
      "Outro": 0
  },
  {
      "ratingDate": "2018-12-23",
      "rate1": 0,
      "rate2": 0,
      "rate3": 0,
      "rate4": 1,
      "rate5": 8,
      "detractor": 0,
      "promoter": 89,
      "nps": 89,
      "Reserva": 0,
      "Abertura": 0,
      "Finalizar": 0,
      "VeiculoSujo": 1,
      "Abastecimento": 0,
      "CheiroCigarro": 0,
      "VagaRuim": 0,
      "Outro": 0
  }
] 

No meu service, tenho método simples para essa chamada:

  getNPS(){
    return this.http.get(API);
  }

No meu componente também é bem simples:

  public npsArray: any[]

  constructor(private npsService: NpsService) {
  }

  ngOnInit() {
    this.getNPS();
  }

  getNPS(){
    this.npsService.getNPS().subscribe((data: any[]) => {
      this.npsArray = data;
      console.log(this.npsArray);
    })
  }

}

No console.log me mostra o JSON certinho, porem se eu tento uma propriedade, por exemplo this.npsArray.VagaRuim, ele me da como undefined

2
  • 1
    Ele e um array de objetos. Tenta this.npsArray[0].VagaRuim.
    – Francisco
    18/01/2019 às 11:31
  • Deu certo, mas como eu faria para percorrer esse objeto em um ngFor por exemplo? 18/01/2019 às 11:40

2 Respostas 2

1

Resolvi, pessoal!

No gfFor, coloquei assim:

{{item['key']}}
0

Tenta mapear o array passando um valor para ele!

public npmArrayMap: any;

getNPS(){
    this.npsService.getNPS().subscribe((data: any[]) => {
      this.npsArray = data;
      console.log(this.npsArray);
      //Passando valor para array com map
      var array = Object.keys(this.npsArray).map(key => ({
                type: key,
                value: this.npsArray[key]
      }));
      this.npmArrayMap = arr;
     console.log(npmArrayMap);
    })
 }

Assim voce também poderá acessá-lo com *ngFor no HTML como no exemplo abaixo.

<ion-item *ngFor="let npm of npmArrayMap ">
  <p>{{ this.npmArrayMap.value.VeiculoSujo }} </p>
</ion-item>   

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .