kyle
kyle

Reputation: 2638

Using *ngIf to resolve to observables

I have two observables in my component $place and $premium, while they are different the template needs both of them to resolve or the page is considered "loading".

In my template I am using *ngIf="($place | async); else loading; let place" which works for place, but I am struggling figure out how to assign $premium to a variable after it resolves.

I have tried adding just doing something like *ngIf="($place | async) && ($premium | async); else loading; let place; let premium" but it will break the assignment for place and premium.

Is there a better way to handle this?

Upvotes: 0

Views: 637

Answers (1)

maxime1992
maxime1992

Reputation: 23793

You can just use combineLatest to create a new Observable like that :

@Component({
  selector: 'my-app',
  template: `
    <div *ngIf="placeAndPremium$ | async as placeAndPremium">
      {{ placeAndPremium.place | json }}
      {{ placeAndPremium.premium | json }}
    </div>
  `,
})
export class App {
  public place$: Observable<any>;
  public premium$: Observable<any>;
  public placeAndPremium$: Observable<any>;

  constructor() {
    this.place$ = Observable.of({somePlace: true}).delay(1000);
    this.premium$ = Observable.of({somePremium: true}).delay(2000);
    this.placeAndPremium$ = this.place$.combineLatest(this.premium$).map(x => ({place: x[0], premium: x[1]}));
  }
}

Here's a working Plunkr : https://plnkr.co/edit/6dtMZevtlDli2Og3gWl9?p=preview

Upvotes: 2

Related Questions