ngFor with Observables?

8.7k Views Asked by At

I am converting an angular 2 component to use asynchronous data sources.

I had a <div class="col s4" *ngFor="let line of lines; let i = index;"> which worked when lines was an Array of Objects, however, lines is now an Observable of an Array of Objects.

This causes error:

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

I tried <div class="col s4" *ngFor="let line of lines | async; let i = index;"> however, that didn't seem to make a difference.

How should I deal with this?

1

There are 1 best solutions below

0
On

Here is an example binding to an observable array. It would be helpful if you posted your controller/component code too.

@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

The answer to the question above is this:

// 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>