【问题标题】:Don't make http call on subsequent button clicks不要在后续按钮点击时进行 http 调用
【发布时间】:2021-12-02 18:24:03
【问题描述】:

我有一个按钮,用户可以单击该按钮进行 http 调用以获取数据。

当用户第一次单击按钮时,我会进行 http 调用。如果用户再次点击该按钮,只需提供之前获取的数据即可。

如何在不将其显式存储在局部变量中的情况下做到这一点?我尝试了几件事,但似乎都没有。它总是发出http请求。我尝试使用“shareReplay”和“share”运算符。

<button (click)=getData()>Click me</button>

getData() {
   source$.pipe(
   switchMap(sourceVal => {
      const source2$ = this.getSource2();
      const source3$ = this.getSource3(); -------- I do not want this call to be made on subsequent button clicks because it's a reference data
      return combineLatest([source2$, source3$])
   }),
   map(([source2Val, source3Val]) => {
      //do some processing
      return 'done'
   })
)
}

我正在使用 angular 和 rxjs。

【问题讨论】:

  • 你能展示一下你尝试过的东西吗?您需要做的就是在第一次调用时将 http 调用的结果存储在某处,然后在后续点击时使用它们。
  • 您可以在点击事件监听器中禁用该按钮,然后在抓取的.then() 阶段启用它。
  • @Redu 不能禁用按钮,用户可以多次点击按钮
  • 你是如何获取数据的?如果您使用任何类型的库,我将首先调查它是否有办法在库中启用缓存以返回以前缓存的数据,而不是发出自己的请求。如果没有,您可能必须在一些持久的全局变量/对象中创建自己的缓存...
  • 查找去抖动和节流。

标签: javascript angular rxjs


【解决方案1】:

您可以禁用按钮或阻止通过变量发送多个请求。

fetching = false;

getData() {
   if(!this.fetching) {
       this.fetching = true;
       this.http.get('url').pipe(shareReplay(1), finalize(() => {
           this.fetching = false;
       }));
   }
}

【讨论】:

  • 好答案,值得一提的是这被称为“去抖动”请求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
  • 2014-11-11
  • 1970-01-01
  • 2018-01-26
相关资源
最近更新 更多