相关疑难解决方法(0)

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

我正在 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() | …
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

12
推荐指数
1
解决办法
5375
查看次数

RxJS publishReplay与publishLast

我正在Angular应用程序中实现缓存HTTP结果.据我所知,下面的代码都有效,但是我需要知道它们是否完全相同,或者我错过了一些重要的东西?

publishLast

getPosts() {
    if( !this.posts$ ) {
      this.posts$ = this.http.get('api').publishLast().refCount();
      return this.posts$;
    }

    return this.posts$;
  }
Run Code Online (Sandbox Code Playgroud)

publishReplay

getPosts() {
  if( !this.posts$ ) {
    this.posts$ = this.http.get('api').publishReplay(1).refCount();
       return this.posts$;
  }

  return this.posts$;
}
Run Code Online (Sandbox Code Playgroud)

javascript rxjs

7
推荐指数
1
解决办法
2971
查看次数

标签 统计

angular ×1

angular-httpclient ×1

javascript ×1

rxjs ×1