ngFor does not give the expected result

Asked

Viewed 88 times

0

My ngFor not showing all the data that arrives, but in the console shows all the results.

I pull some data from the API and it has a sales and meta data, they come in an array and I use the foreach in them, and if it reached the goal it should go to another array:

this.MetaService.FiliaisMetaDiarias().subscribe(
  data => {
    const response = (data as any)
    this.objeto_retorno = JSON.parse(response._body);

    this.objeto_retorno.forEach(element => {

      this.tots = element.TOTAL
      if (this.tots >= this.MetaAtingida) {

        this.fil = [
          {
            FI: element.FILIAL,
            porc: element.TOTAL
          }
        ]

        this.fil.forEach(elements => {
          this.mainColor = 'MetaAtingida'
        })

      }

Then I play in html:

<p [class]="mainColor + ' teste'" *ngFor="let elements of fil" >Filial {{ elements.FI }} = {{ elements.porc }}</p>

It should show all the results, but for some reason it is showing only the last data, but in the console it shows all the data.

Can someone help me?

  • Is there a way you put the code of your service that makes this call? Where is this console in your code that shows the data?

2 answers

2

You’re defining the structure of this.fil every iteration of the foreach.

For example, I’m going to assume that objeto._retorno this is how:

objeto [
   _retorno [
      { "FILIAL": "filial1",
        "porc": "porc1",
        "total": total1 },
      { "FILIAL": "filial2",
        "porc": "porc2",
        "total": total2 }
   ]
]

If the value of the "total" property of the element is greater than the achieved goal, you mark the value of the element to fil.

Then, in the first element, fil would have this value:

fil [
   FI: "filial1",
   porc: "porc1"
]

But in the second, fil will be flagged again, so it looks like this:

fil [
   FI: "filial2",
   porc: "porc2"
]

What you should do is a fil Insert, not check the value of the object to fil. Something like this.fil.append() should solve in this case.

  • Good maybe it would be better to use the map method instead of the foreach tbm

2


The error is here:

this.fil = [
          {
            FI: element.FILIAL,
            porc: element.TOTAL
          }
        ]

You are rebooting this.fil in each iteration of forEach, which means that it will always have only the current element of the iteration, in the case of the last, the last element of the collection.

The correct would be to initialize this.fil out of the loop, and fill with .push in iteration:

this.fil = [];
this.objeto_retorno.forEach(element => {
    this.fil.push({
        FI: element.FILIAL,
        porc: element.TOTAL
    });
 // resto do código...
});
  • 1

    Very well observed =)

Browser other questions tagged

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