简体   繁体   中英

Angular: How to put 2 async subscriptions in ngIf with common else condition

I have a use case wherein I have 2 async subbscriptions with a common else condition.

<ng-container *ngIf="{ data1: data1$ | async, data2: data2$ | async } as history; else loader">
<h2>Inside ngIf condition</h2>
</ng-container>
<ng-template #loader>Loader here....</ng-template>

What's happening here is the content inside the async subscription is being displayed even before the subscription. I understand that is because of the object literal definition of multiple subscriptions.

Is there a way to fix this?

The problem

Something like what you've written is pretty ambiguous.
I'm not sure what semantics you're trying to achieve.

There are many ways to merge Observables (merge, withLatestFrom, forkJoin, zip, etc).
You'll likely have to pick and implement one yourself. Be sure to read the documentation.

Example:

forkJoin [doc] , for example, doesn't emit until its source Observables all complete.

In your component:

joinedData$ = forkJoin({
  data1: this.data1$,
  data2: this.data2$
});

Markup

<ng-container *ngIf="(joinedData$ | async) as history; else loader">
<h2>Inside ngIf condition</h2>
</ng-container>
<ng-template #loader>Loader here....</ng-template>

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