Angular中多个相同的异步管道导致多个http请求 [英] Multiple identical async pipe in Angular causing multiple http requests

查看:30
本文介绍了Angular中多个相同的异步管道导致多个http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的角度应用程序中,我使用异步管道多次渲染组件

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>

问题是导致多个http请求.

The problem is that is causing multiple http request.

我怎么只能使用一个请求?

how can I use only one request ?

推荐答案

方法1

您可以使用 shareReplay 运算符.

共享来源并按订阅重播指定数量的排放.

Share source and replay specified number of emissions on subscription.

import { shareReplay } from 'rxjs/operators';

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


方法2

您可以订阅控制器并在模板中使用该值.


Method 2

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

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

然后在模板中:

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


方法3

您可以将其包装在 ngIf 块中:

<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>

这篇关于Angular中多个相同的异步管道导致多个http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆