0

I have fetched data from backend API, need to loop the data in front end but its value not return.

here is my response from backend API.

[
    [
        {
            "choice": 1,
            "count": 4,
            "percentageValue": "80.0000"
        },
        {
            "choice": 2,
            "count": 1,
            "percentageValue": "20.0000"
        }
    ],
    [
        {
            "choice": 1,
            "count": 4,
            "percentageValue": "80.0000"
        },
        {
            "choice": 2,
            "count": 1,
            "percentageValue": "20.0000"
        }
    ]
]

In ts file

submitPoll(data){
    this.pollService.submitPoll(data).subscribe(response =>{
      this.percentage=response.body;
    });
  }

In html file

<p *ngFor="let percentage of percentage;let i= index;">
                  {{percentage.choice  }}
                </p>

how to use the for loop for array object ? i need to display the percentage in options

2
  • 3
    It's an array of an array. You either need to flatten the inner arrays to one level up or use two nested *ngFors in the template. Commented Apr 13, 2021 at 8:45
  • can you send the answer for above object? Commented Apr 13, 2021 at 8:50

3 Answers 3

1
<ng-template ngFor let-percentItems [ngForOf]="percentage">
    <ng-template ngFor let-items [ngForOf]="percentItems">
        {{ items.choice}} | {{ items.count}} | {{ items.percentageValue}} |<br />
    </ng-template>
</ng-template>

OUTPUT

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

its actually return only first two rows
how to fetch only first array only
this.pollService.submitPoll(data).subscribe(response =>{ this.percentage=response.body; this.percentage = this.percentage.slice(0, 1); });
1

As @MichaelD mentioned, percentage is array of array. A simple solution is to use *ngFor twice.

<div *ngFor="let innerArray of percentage;">
  <p *ngFor="let obj of innerArray;">
    {{obj.choice}}
  </p>
</div>

Comments

1

Assuming response.body is a valid json array as specified you could just use the following to grab the inner items and merge them into a new array for use

const percentages = [].concat(...response.body);

You will then end up with the following for use in your loop

[
  {
    "choice": 1,
    "count": 4,
    "percentageValue": "80.0000"
  },
  {
    "choice": 2,
    "count": 1,
    "percentageValue": "20.0000"
  },
  {
    "choice": 1,
    "count": 4,
    "percentageValue": "80.0000"
  },
  {
    "choice": 2,
    "count": 1,
    "percentageValue": "20.0000"
  }
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.