Home > database >  RxJS operator equivalent of ((observableX | async) || (observableY | async)) in template
RxJS operator equivalent of ((observableX | async) || (observableY | async)) in template

Time:04-28

I have the following code in my component template

<mat-spinner *ngIf="((facade.user.data$.isLoading | async) || (facade.product.data$.isLoading | async))"></mat-spinner>

I want to move this union to the component class as a single property and refer to it from the component template, like so

<mat-spinner *ngIf="detailLoading | async"></mat-spinner>

However, I cannot find which RxJS union operator to use to property represent the condition in the observables

(facade.user.data$.isLoading | async) || (facade.product.data$.isLoading | async)

Which of the RxJS operators could I use to represent the above in my component class?

CodePudding user response:

If you need operator in template (pipe), you can create your own.

I think it should look something like this:

public detailLoading$: Observable<boolean> = this.facade.user.data$.pipe(
    combineLatestWith(this.facade.product.data$),
    map(data => data[0].isLoading || data[1].isLoading )
)

CodePudding user response:

You could assign it to a single variable like this. With combineLatest we emit each time one of the observable emits. We emit one boolean value from each because combineLatest only emits when all have emited at least once (and you may skip it if you wish)

get var$(): Observable<boolean> {
    return combineLatest([
        facade.user.data$.isLoading.pipe(startWith(false)),
        facade.product.data$.isLoading.pipe(startWith(false))
    ]).pipe(
        // skip(1) ,
        map( ([a,b]) => a || b )
    )
}

In template I could do it like this

<ng-container *ngIf="{ isLoading: (var$ | async ) } as foo">
    <mat-spinner *ngIf="foo.isLoading"></mat-spinner>
</ng-container>
  • Related