在模板中使用异步管道会导致 Angular 11 中出现多个请求

RRG*_*T19 12 angular angular-httpclient

我正在 Angular v11.0.2 中做一个 Web 应用程序。我需要进行 HTTP 调用才能在屏幕上显示一些信息。为了节省时间并利用async管道的优势,我在模板中使用它,但是,它导致多个请求永远不会停止。

服务

export class MyDataService {

  constructor(
    private http: HttpClient,
  ) {
  }

  fetchMyEmployeeData(): Observable<any[]> {
    return this.http.post<any[]>('ENDPOINT', {});
  }

}
Run Code Online (Sandbox Code Playgroud)

成分

export class MyAwesomeComponent {

  constructor(
    public myDataService: MyDataService,
  ) {
  }

}
Run Code Online (Sandbox Code Playgroud)

模板

<ng-container *ngIf="(myDataService.fetchMyEmployeeData() | async) as data">
</ng-container>
Run Code Online (Sandbox Code Playgroud)

这会导致多个请求并且永远不会停止。

如果我使用也会发生同样的情况*ngFor

<tr *ngFor="let d of (myDataService.fetchMyEmployeeData() | async)">
  <td>.</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

我已经尝试过以下操作:

使用shareReplay运算符:

fetchMyEmployeeData(): Observable<any[]> {
   return this.http.post<any[]>('ENDPOINT', {}).pipe(shareReplay());
}
Run Code Online (Sandbox Code Playgroud)

使用一个简单的 div:

<div *ngIf="(myDataService.fetchMyEmployeeData() | async) as data">
</div>
Run Code Online (Sandbox Code Playgroud)

我知道如果我从组件订阅并将结果保存在本地变量中,我可以在模板中调用它,但这不是我的目标。工作示例:

export class MyAwesomeComponent implements OnInit {

  data: any[];

  constructor(
    public myDataService: MyDataService
  ) {
  }

  ngOnInit() {
    // This is not my goal because I will need to handle the subscription life manually.
    this.myDataService.fetchMyEmployeeData().subscribe(res => this.data = res);
  }

}
Run Code Online (Sandbox Code Playgroud)

我也遵循了这里给出的建议:

  1. Angular 中多个相同的异步管道导致多个 http 请求
  2. 当没有结果返回时,如何防止 Angular 异步管道频繁进行服务器调用?

我不知道到底是什么导致了多次请求以及如何避免它。

我的目标是使用async模板中的管道并仅执行一次 HTTP 调用。

and*_*pta 10

更新:如果您在模板中多次调用变量,则需要 shareReplay,误解了问题。

shareReplay()应该在组件级别,因为当您调用它时,fetchMyEmployeeData()它是一个返回新 Observables(以及每个新的 shareReplays)的函数

在组件中创建:

employeeData$ = this.myDataService.fetchMyEmployeeData().pipe(shareReplay());
Run Code Online (Sandbox Code Playgroud)

并在模板中使用为

employeeData$ | async
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它只会对后端执行一个请求


归档时间:

查看次数:

5375 次

最近记录:

4 年,1 月 前