gpt4 book ai didi

angular - FormControl debounceTime 在 Angular 5( ionic 3)中不可用

转载 作者:太空狗 更新时间:2023-10-29 17:29:16 26 4
gpt4 key购买 nike

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

还有其他方法可以实现这种延迟吗?

this.searchControl.valueChanges
.debounceTime(2000)
.subscribe(search => this.getCities(search));

最佳答案

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

RXJS 5.5.2 Updates

The recent update of RXJS includes a change in how operators are applied.

Traditionally, operators were applied like this:

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))
}
}

This approach involved modifying the Observable prototype and patching on the methods.

RXJS 5.5 introduces a different way to do this that can lead to significantly smaller code bundles, lettable operators.

To use lettable operators, modify the code from above to look like this:

// 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))
}
}

This slight change allows only import the operators we need in our code. This will result in a smaller, faster application. This example uses Deep Imports, which allow the module we want to import to be isolated.

所以基本上您需要稍微更改导入语句以使用深度导入

从 'rxjs/operators/debounceTime' 导入 { debounceTime };

然后在 pipe(...) 方法中使用 debounceTime:

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

您仍然可以使用旧方法(因为这还不是重大更改),但使用可让运算符会产生更小、更快的应用程序


更新

就像@lifetimes在他的评论中提到(如您所见 here ),此导入

import { switch } from 'rxjs/operators/switchMap';

应该替换为

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

使用较新版本时。

关于angular - FormControl debounceTime 在 Angular 5( ionic 3)中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47472887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com