Angular 2.0.1 AsyncPipe doesn't work with Rx S

2019-07-11 08:45发布

问题:

AsyncPipe works with BehaviorSubject, but I don't want to initialize my service with empty data, for this reason I use Subject intead.

The problem is NgFor and asyncPipe doesn't work with Subject, is it an issue?

This works:

Component:

export class AppComponent {
  foo = new BehaviorSubject<Array<number>>([1,2,3]);

  getFoo(){
     return this.foo.asObservable();
  }
}

Template

<span *ngFor="let e of foo.asObservable() | async">{{e}}</span>

This NOT WORKS:

Component

export class AppComponent {
  foo = new Subject<Array<number>>();

  constructor(){
     setTimeout(() => {
          this.foo.next([1,2,3]);
     }, 3000);
  }

  getFoo(){
     return this.foo.asObservable();
  }
}

Template

<span *ngFor="let e of foo.getFoo() | async">{{e}}</span>

回答1:

The problem here is calling a method from my template - this means every time change detection runs, I'm calling your getFoo() function, which returns a new instance of the observable, which resets the async pipe.

So, the code fails whether you call getFoo() in the NgFor.

Solucion, create an observable variable in the component.