在 module 实现里,务必导入下列 module:
import { ReactiveFormsModule } from '@angular/forms';
template 实现代码:
<input type="text" [formControl]="jerryFormControl"><div>{{ response }}</div>
其中 formControl Directive,绑定的是 FormControl 具体实例。Component 残缺的实现代码:
import { Component, OnInit } from '@angular/core';import { FormControl } from '@angular/forms';import { HttpClient} from '@angular/common/http';import { throttleTime } from "rxjs/operators";// this endpoint is implemented in https://github.com/wangzixi-diablo/ui5-toolset, local.jsconst APIENDPOINT = "http://localhost:3000/echo?data=";@Component({ selector: 'jerryform', templateUrl: './react-form.component.html'})export class JerryReactFormComponent implements OnInit { constructor(private http:HttpClient){} response = ''; onValueChanged = (value)=>{ console.log('new value from live change: ' + value); const url = `${APIENDPOINT}${value}`; const options = { responseType: 'text' as 'json' } var $http = this.http.get(url, options); $http.subscribe( (response:string)=>{ console.log('response from http: ' + response); this.response = response}, (error)=>console.log('error: ' + error)); } ngOnInit(): void { // this.jerryFormControl.valueChanges.pipe(debounceTime(3000)).subscribe(this.onValueChanged); this.jerryFormControl.valueChanges.pipe(throttleTime(2000)).subscribe(this.onValueChanged); } jerryFormControl = new FormControl('');}
在 Component 的实现代码里,咱们并不会间接操作 template 里的 input 标签,而是通过其绑定的 formControl 实例 jerryFormControl 暴露出的 valueChanges Observable,来注册咱们应用程序本人的逻辑,即事件响应函数 onValueChanged.
应用 rxjs/operators 里规范的 throttleTime 操作符,实现 2 秒的函数节流。
最初实现的成果:每当 input 标签页的输出发生变化,触发 onValueChanged 函数,再外面调用我另一个 Github仓库 实现的 echo Service,将 service 结果显示在 input 字段下方。
本文残缺代码在这个 commit 里能找到。
更多Jerry的原创文章,尽在:"汪子熙":