6

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 ?

1 Answer 1

11

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>
Sign up to request clarification or add additional context in comments.

Comments

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.