简体   繁体   English

Angular 4. ngFor和异步问题

[英]Angular 4. ngFor and async issue

I tried to use async pipe and ngFor directive in Angular 4.4. 我试图在Angular 4.4中使用异步管道和ngFor指令。 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." “错误:找不到类型为'object'的其他支持对象'[object Object]'。NgFor仅支持绑定到Iterables,例如数组。”

<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 : 我在Plunker中转载了您的错误:

https://plnkr.co/edit/KpEnf2KOm8XJXurBTjFQ?p=preview 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. NgFor仅支持绑定到Iterables,例如数组。

As already said JB Nizet in a comment below your post, you should check what you really return from the findAll method. 正如JB Nizet在帖子下方的评论中所说的那样,您应该检查一下findAll方法真正返回的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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