FormControl debounceTime在角度5(离子3)中不可用

Saš*_*čič 5 rxjs typescript ionic-framework ionic3 angular

我刚刚从版本4到5更新了离子应用中的角度.我有一些搜索FormControl输入,允许用户通过ajax请求搜索数据库.我使用debounceTime()方法来延迟ajax搜索请求,但在角度升级之后,此方法不再可用.我删除了这个方法调用,但现在在android上的每个用户键上都会发出一个新请求.

有没有其他方法来实现这种延迟?

this.searchControl.valueChanges
        .debounceTime(2000)
        .subscribe(search => this.getCities(search));
Run Code Online (Sandbox Code Playgroud)

seb*_*ras 18

就像你在Ionic docs中看到的那样:

RXJS 5.5.2更新

最近更新的RXJS包括改变运营商的应用方式.

传统上,运营商应用如下:

import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/switchMap';

export MyClass {

  someMethod(){
    // Using Reactive Forms
    this.input.valueChanges
    .debounceTime(500)
    .switchMap(inputVal => this.service.get(inputVal))
    .subscribe(res => console.log(res))
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方法涉及修改Observable原型并修补方法.

RXJS 5.5引入了一种不同的方式来实现这一点,这可以导致明显更小的代码包,可租用的运算符.

要使用lettable运算符,请修改上面的代码,如下所示:

// Use Deep imports here for smallest bunlde size
import { debounceTime } from 'rxjs/operators/debounceTime';
import { switch } from 'rxjs/operators/switchMap'; // <- Please read the update!

export MyClass {

  someMethod(){
    // Using Reactive Forms
    // We use the new `.pipe` method on the observable
    // too apply operators now

    this.input.valueChanges
    .pipe(
      debounceTime(500),
      switchMap(inputVal => this.service.get(inputVal))
    )
    .subscribe(res => console.log(res))
  }
}
Run Code Online (Sandbox Code Playgroud)

这种微小的变化只允许在我们的代码中导入我们需要的运算符.这将导致更小,更快的应用程序.此示例使用Deep Imports,它允许我们要导入的模块被隔离.

因此,基本上您需要稍微更改import语句以使用深度导入

import { debounceTime } from 'rxjs/operators/debounceTime';

然后使用方法的debounceTime内部pipe(...):

this.input.valueChanges
    .pipe(
      debounceTime(500),
      // you can chain more operators if needed ...
      // ...
    )
    .subscribe(res => console.log(res))
Run Code Online (Sandbox Code Playgroud)

您仍然可以使用旧方法(因为这不是一个重大变化),但使用lettable运算符将导致更小,更快的应用程序.


UPDATE

就像@lifetimes在他的评论中提到的那样(正如你在这里看到的),这个导入

import { switch } from 'rxjs/operators/switchMap';
Run Code Online (Sandbox Code Playgroud)

应该被替换

import { switchMap } from 'rxjs/operators/switchMap';
Run Code Online (Sandbox Code Playgroud)

使用较新版本时.


eus*_*tos 5

可以帮助这个例子

let debounce = this.name.valueChanges.pipe(
  debounceTime(1000), // delay 1000 msec
  distinctUntilChanged() // only for changed value
);
debounce.subscribe(changes => {
  console.log(changes);
});
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明