Search code examples
angularrxjsrxjs-observables

Angular 5 + RxJS: using observables in the component without subscribing to them


I normally tend to use Observables in components by passing them into functions through template using myFunction(myObservable$ | async) and it works quite well.

However, in my template I have an output function that emits values to the parent component.

<my-component
   [myInput]="something$ | async"
   (childOutputEmitter)="onChildEmitFunction($event)">
</my-component>

The problem is the onChildEmitFunction() function I need combine both the emitted value ($event) and the myObservable$ | async values.

This doesn't seem to work though:

<my-component
   [myInput]="something$ | async"
   (childOutputEmitter)="onChildEmitFunction($event, (myObservable$ | async))">
</my-component>

Is there a way to pass the value of myObservable$ to onChildEmitFunction() without subscribing to it and storing the value in another variable?


Solution

  • You could use *ngIf directive to use the value from the observable multiple times.

    <ng-container *ngIf="something$ | async as something">
      <my-component
         [myInput]="something"
         (childOutputEmitter)="onChildEmitFunction($event, something)">
      </my-component>
    </ng-container>
    

    Also note that if async pipe is used with HTTP, each pipe could trigger an individual request.