【问题标题】:ngx-select-dropdown how include debounceTime?ngx-select-dropdown 如何包含 debounceTime?
【发布时间】:2020-05-06 06:35:38
【问题描述】:

我需要动态填充我的[options] 数组,一旦用户完成输入,我需要进行 API 调用并获取我的选项列表。

为了避免多次 API 调用,我想使用类似 rxjs debounceTime(1000);

有什么方法可以使用 debounceTime 吗?或者还有其他推荐的选项吗?

【问题讨论】:

    标签: rxjs angular6 ngx-select-dropdown


    【解决方案1】:

    就像 Navruzbek 提到的,“ngx-mat-select-search”可用于服务器端下拉搜索。

    但是,如果您想使用当前库并向其添加 debounceTime,则可以使用 Subject 来解决此问题。喜欢https://stackoverflow.com/a/39960980/7763714的建议

    对我有用的解决方案:

    searchTextChanged=new Subject<string>();
    
    // make the server-side call in the subscrivbe function
    ngOnInit() {
      this.searchTextChanged.pipe( debounceTime(1000), distinctUntilChanged())  .subscribe((value)=> this.outerValuedChanged(value));
    }
    
    addressSearchChanged(searchText: string) {
      if (searchText.length >=3) {
        this.searchTextChanged.next(searchText);
      }
    }
    
    // dummy function
    outerValuedChanged(value: string) {
      console.log('value:', value);
      return 'test';
    }
    &lt;ngx-select-dropdown (searchChange)="addressSearchChanged($event)" formControlName="inputAddressFormControl" [multiple]="false" [config]="config" [options]="addressList"&gt;&lt;/ngx-select-dropdown&gt;

    【讨论】:

      【解决方案2】:

      您可以使用缓冲区和 api 调用而不是 ajax 来使用此技巧

      import { fromEvent, timer } from 'rxjs';
      import { debounceTime, map, buffer, switchMap } from 'rxjs/operators';
      
      let input = document.getElementById('example');
      let input$ = fromEvent(input, 'keyup');
      
      let breakWhen$ = timer(1000);
      let debounceBreak$ = input$.pipe(
      debounceTime( 2000 )
      );
      
      let stream$ = input$.pipe(
        map( ev => ev.key),
        buffer(debounceBreak$),
        switchMap((allTypedKeys) => {
        // do ajax
        console.log('Everything that happened during 2 sec', allTypedKeys)
        return of('ajax based on ' + input.value);
      });
      );
      
      stream$.subscribe((data) => console.log( 'values',data ));
      

      【讨论】:

      • 感谢您的回答。但我面临的问题不是输入字段,而是使用 ngx-select-dropdown。我试图做一些与此非常相似的事情,但是在我去抖动它之后的 onChange 事件,当我尝试映射输入时,它总是未定义。
      • 使用 ngx-mat-select-search(npmjs.com/package/ngx-mat-select-search) 我想这会解决你的问题
      • 这是一个很棒的解决方案。这个库提供的服务器端搜索是完美的。但遗憾的是,由于它需要角度/材质,所以 UI 完全混乱,无法使用。因此,我不能将其标记为正确答案。但我会投票赞成,肯定会帮助别人:)
      猜你喜欢
      • 1970-01-01
      • 2019-10-31
      • 2022-01-27
      • 2019-05-12
      • 2020-04-27
      • 2020-04-03
      • 2021-05-12
      • 1970-01-01
      • 2019-01-21
      相关资源
      最近更新 更多