Observable and ngFor in Angular 2

橙三吉。 提交于 2019-12-13 15:19:31

问题


Below is a simple sample Angular 2 component which uses rxjs Observables.

import { Component , OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import  'rxjs/add/observable/of';

    @Component({
    selector:'ob',
    template: `

    <ul>
        <li *ngFor="let x of obj | async">
            {{x}}
        </li>
    </ul>    
    `
})

export class ObComponent implements  OnInit{

obj:Observable<number>;

ngOnInit() {
this.obj = Observable.of(1,2,3,4);
}

} 

This component throws below error

inline template:15:12 caused by: Cannot find a differ supporting object '4' of type 'number'. NgFor only supports binding to Iterables such as Arrays.

Any idea what could be the issue ?


回答1:


Observable.of. emits values in a sequence so *ngFor receives single values through async instead of the array that *ngFor expects.

Use

obj:Observable<number[]>;//declare

Observable.of([1,2,3,4])


来源:https://stackoverflow.com/questions/42856913/observable-and-ngfor-in-angular-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!