ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-06-05 15:05:35  阅读:198  来源: 互联网

标签:http Form value response Reactive onValueChanged import Angular angular


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

标签:http,Form,value,response,Reactive,onValueChanged,import,Angular,angular
来源: https://www.cnblogs.com/sap-jerry/p/14852742.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有