简体   繁体   English

Angular RxJS防止双重API调用

[英]Angular RxJS prevent double API calls

I want to re-use the result of an RxJS stream without executing it again. 我想重新使用RxJS流的结果,而无需再次执行它。

In a component I have to Input() streams: query$ and category$ . 在组件中,我必须输入()流: query$category$ I want to convert that into two streams that share the same API source. 我想将其转换为共享相同API源的两个流。 Right now it is making two requests. 目前,它正在发出两个请求。 I'd like to have only one request. 我只想提出一个要求。

Simplified code: 简化代码:

this.searchResults$ = this.query$
  .switchMap((query) => this.httpClient.get(`/whatever?q=${query}`));

this.filteredSearchResults$ = Observable
  .combineLatest(this.searchResults$, this.category$)
  .filter(([ searchResults, category ]) => {
    // Code to make a subset

    return ['a', 'subset'];
  });

I consume both searchResults$ and filteredSearchResults$ in the same component: 我在同一组件中同时使用了searchResults $和filteredSearchResults $:

<ng-container *ngIf="(searchResults$ | async) as searchResults">
  <ng-container *ngIf="(filteredSearchResults$ | async) as filteredSearchResults">
  </ng-container>
</ng-container>

Now I understand why there are two API calls. 现在,我了解了为什么有两个API调用。 I just don't see any way to prevent it. 我只是没有任何方法可以阻止它。

You might want to use share : 您可能要使用share

this.searchResults$ = this.query$
  .switchMap((query) => this.httpClient.get(`/whatever?q=${query}`))
  .share(); <-- HERE

this.filteredSearchResults$ = Observable
  .combineLatest(this.searchResults$, this.category$)
  .filter(([ searchResults, category ]) => {
    // Code to make a subset

    return ['a', 'subset'];
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM