Élodie Petit
Élodie Petit

Reputation: 5914

Can not bind to an Observable array

I'm using Angular 2 and trying to do some filtering on the array elements before viewing them on the page. The service returns the list of some players with this call:

getPlayers(position: string) {
    return this.get(`players/${position}`)
        .map(r => Observable.from(r.data))
        .catch(error => {
            console.log('Error: ', error);
            return Observable.of<any>();
        });
}

As far as I can tell, this returns an ArrayObservable object.

This is how I consume the service in the component:

this.svc.getPlayers(this.position)
  .subscribe(p => this.players = p); // this.players is Array<Player>

The shape of the data I get from the service is:

{
  "success": true,
  "data": [
   ...
  ]
}

So after all of these steps, I get the error below:

Cannot find a differ supporting object '[object Object]' of type 'Player 1'. NgFor only supports binding to Iterables such as Arrays.

So what's going on here?

Upvotes: 1

Views: 1106

Answers (1)

Alexander Ciesielski
Alexander Ciesielski

Reputation: 10824

Cannot find a differ supporting object '[object Object]' of type 'Player 1'. NgFor only supports binding to Iterables such as Arrays.

This means you are binding your *ngFor to an object, rather than an array. Looking at your HTTP call, you return an Observable of an array, rather than an Array.

        .map(r => Observable.from(r.data))

Change this line to

        .map(r => r.data)

.map() already returns an Observable, you don't need to wrap the result in an Observable again.

Upvotes: 1

Related Questions