使用* ngIf解析为可观察对象

时间:2017-05-05 16:29:05

标签: angular asynchronous rxjs observable

我的组件$place$premium中有两个可观察对象,虽然它们不同,但模板需要它们才能解析或者页面被视为" loading"。

在我的模板中,我使用*ngIf="($place | async); else loading; let place"适用于地方,但我很难弄清楚如何在变量结算后将$premium分配给变量。

我尝试过添加*ngIf="($place | async) && ($premium | async); else loading; let place; let premium"之类的内容,但会破坏地点和高级版的分配。

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以使用combineLatest创建一个新的Observable:

@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]}));
  }
}

这是一个有效的普朗克:https://plnkr.co/edit/6dtMZevtlDli2Og3gWl9?p=preview