简体   繁体   中英

Sending Latest http Request when previous call finishes in Angular

I am trying to accomplish the following:

I have a request form with say 4 fields (A, B, C, D) for updating a ticket. Whenever a user exits a field (after typing something) a request should be sent to the server to update that ticket. However, imagine the following scenario:

  • The user updates field A
  • A request is sent to the server to update the ticket.
  • User updates B and then C before the update call for A finishes

In this case I only want the latest call (update for field C) sent to the server and not before reply from A has finished. I have tried to illustrate this below.

在此处输入图像描述

I have read several places about debouncing and throttling, but I cannot seem to wrap my head around the perfect solution as this is firstly not based on time and secondly it should not ignore events while the current one is in progress which seems to exclude both of them.

I thought about implementing sort of a buffer with room for one item only, but I figured there had to be a better solution.

Any input is much appreciated, thanks!

Looks like you need the rxjs switchmap operator. Switchmap will replace the current request observable with a new one every time your input observable emits new data. While this happens the first request will be cancelled.

const requestObservable$ = inputObservable$.pipe(
  switchmap(yourInputData => this.http.post("...url",yourInputData))
);
requestObservable$.subscribe(response => console.log(response));

The requestObservable$ will respond with the latest data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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