ngFor with Observables?

时间:2017-01-03 17:21:01

标签: node.js angular typescript angular2-observables

我正在转换角度2组件以使用异步数据源。

<div class="col s4" *ngFor="let line of lines; let i = index;">是一个对象数组时,我有一个lines,但是,行现在是一个对象数组的Observable。

这会导致错误:

  

找不到不同的支持对象&#39; [object Object]&#39;类型&#39;对象&#39;。 NgFor仅支持绑定到Iterables,例如Arrays。

我试过<div class="col s4" *ngFor="let line of lines | async; let i = index;">然而,这似乎并没有什么不同。

我该如何处理?

1 个答案:

答案 0 :(得分:2)

以下是绑定到可观察数组的示例。如果您发布了控制器/组件代码也会有所帮助。

@Component({
   selector: 'my-app',
   template: `
   <div>
     <h2>Wikipedia Search</h2>
     <input type="text" [formControl]="term"/>
     <ul>
       <li *ngFor="let item of items | async">{{item}}</li>
     </ul>
   </div>
 `
 })
export class App {

   items: Observable<Array<string>>;
   term = new FormControl();

   constructor(private wikipediaService: WikipediaService) {
        this.items = this.term.valueChanges
             .debounceTime(400)
             .distinctUntilChanged()
             .switchMap(term => this.wikipediaService.search(term));
    }
 }

http://blog.thoughtram.io/angular/2016/01/07/taking-advantage-of-observables-in-angular2-pt2.html

Using an array from Observable Object with ngFor and Async Pipe Angular 2

上述问题的答案是:

// in the service
getItems(){
    return Observable.interval(2200).map(i=> [{name: 'obj 1'},{name: 'obj 2'}])
}

// in the controller
Items: Observable<Array<any>>
ngOnInit() {
    this.items = this._itemService.getItems();
}

 // in template
 <div *ngFor='let item of items | async'>
      {{item.name}}
 </div>
相关问题