简体   繁体   English

发送最新的 http 请求,当前一个呼叫在 Angular 中完成时

[英]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.我有一个请求表,其中包含 4 个字段(A、B、C、D)用于更新票证。 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
  • A request is sent to the server to update the ticket.向服务器发送请求以更新票证。
  • User updates B and then C before the update call for A finishes在对 A 的更新调用完成之前,用户更新 B,然后更新 C

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.在这种情况下,我只想将最新的调用(字段 C 的更新)发送到服务器,而不是在 A 的回复完成之前发送。 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映射运算符。 Switchmap will replace the current request observable with a new one every time your input observable emits new data.每次您的输入 observable 发出新数据时, Switchmap都会用新的请求 observable 替换当前请求。 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. requestObservable$将响应最新数据。

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

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