Multiple identical async pipe in Angular causing multiple http requests

ⅰ亾dé卋堺 提交于 2021-01-27 07:16:42

问题


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:


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>


来源:https://stackoverflow.com/questions/56278367/multiple-identical-async-pipe-in-angular-causing-multiple-http-requests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!