因为ngmodel正在立即更新如何放置延迟。
<input type="text" value="{{item.task_name}}" name="task_name" [(ngModel)]="item.task_name" (ngModelChange)="update_fields([item.task_name])" >
我需要通过调用update_fields((延迟一秒钟来保存task_name,以避免即时呼叫服务。
谢谢
rxjs 和 observables 是此类任务的理想选择!这是如何实现它的示例:
模板:
<input type="text" [value]="item.task_name"(keyup)="term$.next($event.target.value)">
组件:
import ......
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
@Component{(
...
)}
export class YourComponent {
term$ = new Subject<string>();
constructor() {
this.term$
.debounceTime(1000)
.distinctUntilChanged()
.switchMap(term => /*do something*/);
}
}
subject
是一种既可以观察和观察者的对象的类型 - 这意味着您可以订阅它并从中发出值(使用next()
(!
debounceTime
等待MS中提供的时间,直到允许新更改
distinctUntilChanges
不允许相同的输入通过两次。
switchMap
从链条中获取最新观察的可观察,因此您不会一次获得多个结果
fredrik lundin的答案已更新了Angular 6:
模板:
<input type="text" [value]="item.task_name" (keyup)="term$.next($event.target.value)">
组件:
import ......
import { Subject, EMPTY } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
@Component{(
...
)}
export class YourComponent implements OnDestroy {
term$ = new Subject<string>();
private searchSubscription: Subscription;
constructor() {
this.searchSubscription = this.term$.pipe(
debounceTime(1000),
distinctUntilChanged(),
switchMap(term => {
/*do something*/
return EMPTY;
})
).subscribe();
}
ngOnDestroy() {
//remember to unsubscribe on destroy
if (this.searchSubscription) {
this.searchSubscription.unsubscribe();
this.searchSubscription = null;
}
}
}
使用setTimeout()
大量解决方案,但这将导致每次模型更改时调用该功能,一种简单的方法是防止这种情况
,例如
timeOut;
timeOutDuration = 1000;
update_fields(data) {
clearTimeout(this.timeOut);
this.timeOut = setTimeout(() => {
//do something
}, this.timeOutDuration);
}
进行最后一次更新后仅调用一次函数,并且timeOutDuration
已通过
update_fields(){
this.service.yourTask(){
.subscribe(data => {
setTimeout(()=>{ //your task }, 4000)
}
}
}
someFunction() {
setTimeout(() => /* code to execute */, 3000)
}