在AngularJS中,我可以使用ng-model选项去抖模型.
ng-model-options="{ debounce: 1000 }"
Run Code Online (Sandbox Code Playgroud)
如何在Angular中去抖模型?我试图在文档中搜索debounce,但我找不到任何东西.
https://angular.io/search/#stq=debounce&stp=1
一个解决方案是编写我自己的去抖函数,例如:
import {Component, Template, bootstrap} from 'angular2/angular2';
// Annotation section
@Component({
selector: 'my-app'
})
@Template({
url: 'app.html'
})
// Component controller
class MyAppComponent {
constructor() {
this.firstName = 'Name';
}
changed($event, el){
console.log("changes", this.name, el.value);
this.name = el.value;
}
firstNameChanged($event, first){
if (this.timeoutId) window.clearTimeout(this.timeoutID);
this.timeoutID = window.setTimeout(() => {
this.firstName = first.value;
}, 250)
}
}
bootstrap(MyAppComponent);
Run Code Online (Sandbox Code Playgroud)
而我的HTML
<input type=text [value]="firstName" #first (keyup)="firstNameChanged($event, first)">
Run Code Online (Sandbox Code Playgroud)
但是我正在寻找一个内置函数,Angular中有一个吗?
我正在尝试调用输入加密事件的服务.
HTML
<input placeholder="enter name" (keyup)='onKeyUp($event)'>
Run Code Online (Sandbox Code Playgroud)
以下是onKeyUp()功能
onKeyUp(event) {
let observable = Observable.fromEvent(event.target, 'keyup')
.map(value => event.target.value)
.debounceTime(1000)
.distinctUntilChanged()
.flatMap((search) => {
// call the service
});
observable.subscribe((data) => {
// data
});
}
Run Code Online (Sandbox Code Playgroud)
从浏览器的网络选项卡中可以看出,它正在调用每个按键事件的键盘功能(正如它应该做的那样),但我想要实现的是每个之间1秒的去抖时间.服务电话.此外,如果我移动箭头键移动,则会触发事件.
我正在尝试在Angular 5函数上使用debounceTime,但不确定如何使用它。构建搜索功能时,可以使用它,因为它绑定到对该输入值所做的更改,如下所示:
this.search
.debounceTime(400)
.distinctUntilChanged()
.takeUntil(this.onDestroy)
.subscribe((model) => {
return this.filterArray(model);
});
Run Code Online (Sandbox Code Playgroud)
但是现在我想将其应用于一个函数,该函数在很多地方都被调用过,并通过http post将事件发送到数据库,如下所示:
private saveData(): void {
this.http.post('event/url', data).takeUntil(this.onDestroy).subscribe((response: Response) => {
// -
}, error => {
// -
});
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?saveData().debounceTime()还是我需要以其他方式做到这一点?