Angular 4,如何以1秒的延迟更新[(ngModel)] [英] Angular 4, How to update [(ngModel)] with a delay of 1 seconds

查看:142
本文介绍了Angular 4,如何以1秒的延迟更新[(ngModel)]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ngModel立即更新了延迟设置方法.

Since ngModel is updating instantly how to put a delay.

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

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

I need to save the task_name with a delay of one seconds by calling update_fields() , To avoid instant calls to service.

谢谢

推荐答案

Rxjs Observables 是此类任务的理想选择!这是一个如何实现的示例:

Rxjs and Observables are the perfect candidate for this type of task! Here is an example of how it can be achieved:

模板:

<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())!

subject is a type of object that acts both as an observable and observer - meaning you can both subscribe to it and emit values from it (with next())!

debounceTime等待提供的时间(以毫秒为单位),直到允许进行新更改为止

debounceTime waits for the provided time in ms until it allows for new changes

distinctUntilChanges不允许同一输入连续两次通过

distinctUntilChanges will not allow the same input to pass through two times in a row

switchMap从链中获取最新的可观测数据,因此您不会一次获得多个结果

switchMap takes the latest observable from the chain so you don't get multiple results at once

这篇关于Angular 4,如何以1秒的延迟更新[(ngModel)]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆