Victor Marchuk Victor Marchuk - 1 year ago 88
Javascript Question

Angular 2 AsynPipe isn't working with an Observable

I'm getting the following error:

EXCEPTION: Cannot find a differ supporting object '[object Object]' in [files | async in Images@1:9]

Here's the relevant part of the template:

<img *ngFor="#file of files | async" [src]="file.path">

Here's my code:

export class Images {
public files: any;
public currentPage: number = 0;
private _rawFiles: any;

constructor(public imagesData: ImagesData) {
this.imagesData = imagesData;
this._rawFiles = this.imagesData.getData()
.flatMap(data => Rx.Observable.fromArray(data.files));

nextPage() {
let imagesPerPage = 10;
this.currentPage += 1;
this.files = this._rawFiles
.skip((this.currentPage - 1) * imagesPerPage)
console.log("this.files:", this.files);

at the end shows that it's an observable:

last console.log

return a regular RxJS observable from Angular's
service, so why wouldn't async pipe work with it? Maybe the way I'm using
is wrong and it messes something up?

If I try to subscribe to this observable like that:

this.files = this._rawFiles
.skip((this.currentPage - 1) * imagesPerPage)
.subscribe(file => {
console.log("file:", file);

It prints a list of objects as expected:

enter image description here

Answer Source

Try with an Observable<File[]> instead:

this.files = this._rawFiles
         .skip((this.currentPage - 1) * imagesPerPage)
         .map(file => [file])
         .scan((acc,value) => acc.concat(value))

This should require no manual code to subscribe and should work perfectly with your current template.

I do something very similar in this blog post.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download