Angular 6 Undefined property in JSON

Asked

Viewed 235 times

1

I consume an API that returns a JSON to me. The return works perfectly, however, when I try to access some property of this JSON, it gives me as Undefined. I already JSON and is 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
  }
] 

In my service, I have simple method for this call:

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

In my component is also very simple:

  public npsArray: any[]

  constructor(private npsService: NpsService) {
  }

  ngOnInit() {
    this.getNPS();
  }

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

}

In the console.log shows me the right JSON, but if I try a property, for example this.npsArray.Vagamau, it gives me as Undefined

  • 1

    It is an array of objects. Try this.npsArray[0].VagaRuim.

  • It worked, but how would I go through this object in an ngFor for example?

2 answers

1

I got it, guys!

In the gfFor, put like this:

{{item['key']}}

0

Tries to map the array by passing a value to it!

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

So you can also access it with *ngFor in the HTML as in the example below.

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

Browser other questions tagged

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