微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular Reactive Form 的一个具体使用例子

在 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.js

const 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的原创文章,尽在:"汪子熙":

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐