简体   繁体   English

不要在随后的按钮点击时调用 http

[英]Don't make http call on subsequent button clicks

I have a button user can click on that makes an http call to fetch data.我有一个按钮,用户可以点击它来调用 http 来获取数据。

When user click the button the first time, I make http call.当用户第一次单击按钮时,我拨打 http 电话。 But I do not want to make the call again and just provide the data that was fetched earlier if the user decides to click the button again.但是我不想再次拨打电话,如果用户决定再次点击按钮,我只想提供之前获取的数据。

How do I do that?我怎么做? I have tried few things but none seem to work.我尝试了几件事,但似乎都没有。 It always makes the http request.它总是发出 http 请求。 I have tried to use "shareReplay" and "share" operators.我曾尝试使用“shareReplay”和“share”运算符。

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

getData() {
   return this.http.get('url').pipe(shareReplay(1));
}

I am using angular and rxjs.我正在使用 angular 和 rxjs。

This is what my actual code looks like.这就是我的实际代码的样子。

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'
   })
)
}

you can disable the button or prevent sending multiple requests via a variable.您可以禁用按钮或阻止通过变量发送多个请求。

fetching = false;

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

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

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