Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple identical async pipe in Angular causing multiple http requests

Tags:

angular

rxjs

In my angular app I'm using async pipe to render acomponent multiple times

<app-main-chart  [type]="type" [name]="Name" [values]="values$ | async" [objectifs]="dataObjectifs"></app-main-chart>
...
...
<app-main-chart  [type]="type" [name]="Name" [values]="values$ | async" [objectifs]="dataObjectifs"></app-main-chart>

The problem is that is causing multiple http request.

how can I use only one request ?

like image 988
Hamza Haddad Avatar asked May 23 '19 15:05

Hamza Haddad


1 Answers

Method 1

You can use shareReplay operator.

Share source and replay specified number of emissions on subscription.

import { shareReplay } from 'rxjs/operators';

values$ = source
  .pipe(
    shareReplay()
  );

Method 2

You can subscribe in the controller and use that value in the template.

ngOnInit() {
  this.values$.subscribe(values => this.values = values);
}

Then in the template:

<app-main-chart [type]="type" 
                [name]="Name" 
                [values]="values" 
                [objectifs]="dataObjectifs">
</app-main-chart>

Method 3

You can wrap it in ngIf block:

<div *ngIf="values$ | async as values">
  <app-main-chart [type]="type" 
                  [name]="Name" 
                  [values]="values" 
                  [objectifs]="dataObjectifs">
  </app-main-chart>
  <app-main-chart [type]="type" 
                  [name]="Name" 
                  [values]="values" 
                  [objectifs]="dataObjectifs">
  </app-main-chart>
</div>
like image 72
s.alem Avatar answered Sep 22 '22 18:09

s.alem