Mukil Deepthi
Mukil Deepthi

Reputation: 6452

Angular calling async pipe makes http call that many time

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>

Upvotes: 3

Views: 1464

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

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.

Upvotes: 4

Related Questions