简体   繁体   English

RXJS 去抖 ajax 调用

[英]RXJS debounce ajax calls

Hi using React and I've got this code in a component that does a query when an external entity name changes.嗨,使用 React,我在一个组件中得到了这段代码,当外部实体名称更改时,它会进行查询。 So it comes from another input somewhere in the app.所以它来自应用程序某处的另一个输入。 When it change my other component gets update and run that request.当它更改时,我的其他组件会更新并运行该请求。 The external input is already debounce at 250ms, but I want to debounce this code to make sure I don't sent too much request to server for nothing.外部输入已经在 250 毫秒时去抖动,但我想对这段代码进行去抖动,以确保我不会无缘无故地向服务器发送太多请求。 I use debounceTime(5000) there to test it, but it just happen instantly.我在那里使用 debounceTime(5000) 来测试它,但它只是立即发生。 My server is local for now, so it's very fast to get a response.我的服务器现在是本地的,所以得到响应非常快。 I wonder what I'm doing wrong with the debounceTime function.我想知道我在 debounceTime function 上做错了什么。

    const url = formField.getRequest(entity);
    const headers = Headers.getDefaultHeaders(context);
    headers.Accept = 'application/json';
    headers['Content-Type'] = 'application/json';
    ajaxObservable = ajax({
      url,
      method: 'get',
      headers,
    }).pipe(
      debounceTime(5000),
      map((response) => {
        const options = formField.parseResponse(response.response);
        doneCB(options.sort());
      }),
      catchError(() => of({})),
    );

    ajaxObservable.subscribe(() => {});```

Thanks a lot!

If you are not sure if the input is denounced:如果您不确定输入是否被谴责:

import { of, fromEvent } from 'rxjs'; 
import { map, tap, delay, switchMap, debounceTime } from 'rxjs/operators';

const input = document.querySelector('#search');
const fakeRequest$ = of('Requested').pipe(delay(1500))

fromEvent(input, 'keydown')
.pipe(
  tap((event) => console.log('Before debounceTime', event.target.value)),
  debounceTime(500),
  tap((event) => console.log('After debounceTime', event.target.value)),
  switchMap(() => fakeRequest$),
  tap(console.log),
)
.subscribe()

stackblitz堆栈闪电战

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

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