Angular 2中的Observable和ngFor [英] Observable and ngFor in Angular 2

查看:89
本文介绍了Angular 2中的Observable和ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是使用rxjs Observables的简单示例Angular 2组件.

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

} 

此组件引发以下错误

内联模板:15:12由以下原因引起:无法找到类型为"number"的其他支持对象"4".NgFor仅支持绑定到数组等Iterable.

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 ?

推荐答案

Observable.of.发出序列中的值,因此 * ngFor 通过异步接收单个值,而不是 * ngFor 期望的数组.

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

使用

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

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

这篇关于Angular 2中的Observable和ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆