2017-09-30 63 views
0

我尝试在Angular 4.4中使用异步管道和ngFor指令。 它工作正常,但我在控制台中得到奇怪的错误信息:Angular 4. ngFor和异步问题

“错误:无法找到类型为'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(); 
    } 
} 

请告知

+0

'* ngFor'只迭代数组,但不支持迭代对象。你可以使用如图所示的管道https://stackoverflow.com/questions/41396435/how-to-iterate-object-object-using-ngfor-in-angular-2/41396558#41396558 –

+2

实际上由findAll()返回的observable似乎是对象,而不是数组。检查你真的从那个方法返回(在运行时)。 –

+0

那么,findAll方法返回数组的Observable。所以ngFor实际显示返回的数据。唯一的问题是控制台中的错误消息。 – Sergey

回答

1

我转载的Plunker您的错误:

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

要创建的错误,我做我的服务方法返回一个对象,而不是预期的数组:

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

然后,我打电话给方法从组件:

@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(); 
    } 
} 

而且我得到了

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

前面已经说过JB Nizet在下面的信息发表评论时,你应该检查你真正从的findAll方法返回。

+0

谢谢你,阿普。事实证明,我在页面上有两个* ngFor(用于桌面和移动版本)。 Second * ngFor错过了异步管道,所以它被隐藏了,但仍然出现错误。 – Sergey