简体   繁体   中英

Angular 4. ngFor and async issue

I tried to use async pipe and ngFor directive in Angular 4.4. It works fine but I got weird error message in console:

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

<table>
  <tbody>
  <tr *ngFor="let event of events | async">
  </tr>
  </tbody>
 </table>


export class EventsComponent {

  events: Observable<Array<Event>>;

  constructor(private eventService: EventService) {
      this.events = this.eventService.findAll();
  }
}

Please advise

I reproduced your error in a Plunker :

https://plnkr.co/edit/KpEnf2KOm8XJXurBTjFQ?p=preview

To create the error, I made my service method return an object instead of the expected array :

findAll(): Observable<Array<string>> {
  return Observable.of({ data: ['Francis', 'Emilie', 'Diego'] });
}

Then, I called the method from the component :

@Component({
  selector: 'my-app',
  template: `
    <div>
      <ul>
        <li *ngFor="let name of names | async">{{ name }}</li>
      </ul>
    </div>
  `,
})
export class App implements OnInit {

  names: string;

  constructor(private eventService: EventService) { }

  ngOnInit(): void {
    this.findAll();
  }

  findAll(): void {
    this.names = this.eventService.findAll();
  }
}

And I got

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

As already said JB Nizet in a comment below your post, you should check what you really return from the findAll method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM