3

I am using async pipe in the template. If you see my below code i am using async pipe in two different places. Because it is used in two places, it gets subscribed two time and there are two http calls made. How to avoid this one single call with async pipe? I was able to achieve without async by subscribe in ngOnInit() but would like to know how to achieve with single async pipe in my case?

<div class="flex-group space-between">
    <h1>Heading</h1>

    <div *ngIf="historyYears$ | async as historyYears; else loadingComponent">
      <aa-alert alertClass="info" alertText="You have no training history" *ngIf="historyYears.length === 0"></aa-alert>
    </div>
  </div>
  
  <div *ngIf="historyYears$ | async as historyYears; else loadingComponent">
  <!--rest of code goes here -->
  </div>
  
  <ng-template #loadingComponent>
    <app-loading></app-loading>
  </ng-template>

1 Answer 1

4

Here are a couple ways to prevent your http call from firing twice:

1. Use the shareReplay operator

Component:

public historyYears$ = this.someService.historyYears$.pipe(shareReplay());

This will cause multiple subscriptions to the same observable to share a single subscription.

2. Use a single async pipe

<ng-container *ngIf="historyYears$ | async as historyYears">

  <div class="flex-group space-between">
    <h1>Heading</h1>

    <div *ngIf="historyYears; else loadingComponent">
      <aa-alert alertClass="info" alertText="You have no training history" *ngIf="historyYears.length === 0"></aa-alert>
    </div>
  </div>
  
  <div *ngIf="historyYears; else loadingComponent">
    <!--rest of code goes here -->
  </div>
  
  <ng-template #loadingComponent>
    <app-loading></app-loading>
  </ng-template>

</ng-container>

Here we move the *ngIf that uses the async pipe up to a common parent of all elements that need access to historyYears.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree it was stated in the question already. I'll delete my comment :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.