* ngIf with several async pipe variables

Trying to combine two observables into one *ngIfand show the user interface when both *ngIf.

Take:

<div *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
    <b>{{userLanguage.language}}</b> and <b>{{userLanguage.user}}</b>
</div>

From: putting two asynchronous subscriptions in one Angular * ngIf statement

This works as far as it compiles, however in my case language$it user$will be from two HTTP requests, and it seems to user$throw runtime errors like TypeError: _v.context.ngIf.user is undefined.

Essentially, I really want (this does not work):

<div *ngIf="language$ | async as language && user$ | async as user">
    <b>{{language}}</b> and <b>{{user}}</b>
</div>

This is the best solution:

  • Subscribe inside a component and write to variables
  • To combine the two observables within a component, say, with withLatestFrom
  • Add null checks {{userLanguage?.user}}
+11
source share
2 answers

ngIf:

<ng-container *ngIf="language$ | async as language">
  <div *ngIf="user$ | async as user">
    <b>{{language}}</b> and <b>{{user}}</b>
  </div>
<ng-container>

, HTTP- .

- language user , :

<ng-container *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
  <ng-container *ngIf="userLanguage.language as language">
    <ng-container *ngIf="userLanguage.user as user">
      <div><b>{{language}}</b> and <b>{{user}}</b></div>
    </ng-container>
  </ng-container>
</ng-container>

- , , withLatestFrom

+24

, , , forkJoin .

https://www.learnrxjs.io/operators/combination/forkjoin.html

ForkJoin , Observable ,

Observable.forkJoin(
  Observable.of("my language").delay(1000),
  Observable.of("my user").delay(1000),
).subscribe(results => {
  this.language = results[0]
  this.user = results[1]
})

onError .

+4

Source: https://habr.com/ru/post/1689564/


All Articles