Errand
Errand

Reputation: 129

Can't display multiple object in *ngFor loop

I have received some data throught an API call and then I converted them to display them on my angular template but it shows me an empty object, here is my objects what's they looks like:

enter image description here

and this is my store.ts code what looks like:

export class Store implements OnInit {
  store: Store[];
ngOnInit() {
    this.getStore();
  }

  getStore() {
    this.storeService.getAll().subscribe(((response: Store[]) => {
      let data = response['data'];
      for(let  obj in data ) {
        this.store =  data[obj];
        console.log(this.store)
      }
    }));
}

and here is my store.html layout:

<div*ngFor="let key of store | keyvalue ; let i = index" >
        <ul 
            (click)="onPatch(i)">
            <li>{{key.name}}</li>
            <span>{{key.date}}</span>
        </ul>
    </div>

UPDATED:

if I make like this:

this.store= response['data'];
    console.log(this.store);

it will give me a dynamic object like the screenshot bellow and that's why I made my operation on that object:

enter image description here

Upvotes: 0

Views: 738

Answers (3)

Wilhelmina Lohan
Wilhelmina Lohan

Reputation: 3043

As @DeborahK states based on the info you've given us response.data contains the array

https://stackblitz.com/edit/angular-cant-display-multiple-object-in-ngfor-loop?file=src%2Fapp%2Fapp.component.ts

It works here ^ maybe you can fork that and modify to show the issue.

Upvotes: 0

itsundefined
itsundefined

Reputation: 1450

The loop that you have inside the subscription of the http request override each previous object and you end up keeping only the last one when the loop ends. You should remove that loop and then it will work just fine.

Upvotes: 1

DeborahK
DeborahK

Reputation: 60626

If data already contains your array, can you just do this:

  getStore() {
    this.storeService.getAll().subscribe(((response: Store[]) => {
      this.store = response['data'];
    }));

Upvotes: 2

Related Questions