Angular 4,如何以1秒的延迟更新[(ngModel)]

11 ngmodel angular

由于ngModel即时更新如何延迟.

  <input type="text" value="{{item.task_name}}" name="task_name" [(ngModel)]="item.task_name" (ngModelChange)="update_fields([item.task_name])" >
Run Code Online (Sandbox Code Playgroud)

我需要通过调用update_fields()来保存task_name,延迟时间为1秒,以避免即时调用服务.

谢谢

Fre*_*din 21

RxjsObservables是这类任务的完美候选者!以下是如何实现它的示例:

模板:

<input type="text" [value]="item.task_name"(keyup)="term$.next($event.target.value)">
Run Code Online (Sandbox Code Playgroud)

零件:

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*/);
  }
}
Run Code Online (Sandbox Code Playgroud)

subject是一种对象,既可以作为观察者也可以作为观察者 - 这意味着你可以订阅它并从中发出值(带next())!

debounceTime 等待提供的时间以毫秒为单位,直到它允许新的更改

distinctUntilChanges 不允许相同的输入连续两次传递

switchMap 从链中获取最新的observable,这样您就不会立即获得多个结果

  • 我只是使用`subscribe`而不是`switchMap`而且它有效. (4认同)

van*_*ras 10

Fredrik Lundin 为 Angular 6 更新的回答:

模板:

<input type="text" [value]="item.task_name" (keyup)="term$.next($event.target.value)">
Run Code Online (Sandbox Code Playgroud)

成分:

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)