简体   繁体   中英

Angular4 async pipe with ngFor

I've this ngFor in my component:

<li *ngFor="let item of items$ | async">
     {{item}}
    </li>

Here is my component code:

this.items$ = Observable.of(true)
    .flatMap((shouldPresentNumbers) => {
      if(shouldPresentNumbers)
         return  Observable.forkJoin(Observable.of(1,2,3,4,5));
    });

My goal is to render items asynchronically. Means that I need that items$ would get an object of type Observable<Array<any>> . Unfortunately, after running the code above i'm gettin only a single observable to items$ (Observable of the last value -> 5).

How can I return an Observable of [1,2,3,4,5] ?

Okay let's discuss this construction:

Observable.forkJoin(Observable.of(1,2,3,4,5))

Observable.of() produces one Observable which emits 5 items in a row. fork-join waits until it completes and then returns the last item which is 5. What you need is an Observable with an array of 5 items:

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

So, you can simplify your code this way:

this.items$ = Observable.of(true)
    .flatMap((shouldPresentNumbers) => Observable.of(shouldPresentNumbers ? [1,2,3,4,5] : []));

Plunkr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM