首页 > Web开发 > 详细

ReactiveX 学习笔记(22)使用 RxJS + Angular 进行 GUI 编程

时间:2018-09-02 17:53:06      阅读:151      评论:0      收藏:0      [点我收藏+]

课题

  1. 程序界面由3个文本编辑框和1个文本标签组成。
  2. 要求文本标签实时显示3个文本编辑框所输入的数字之和。
  3. 文本编辑框输入的不是合法数字时,将其值视为0。
  4. 3个文本编辑框的初值分别为1,2,3。

创建工程

# 安装 Angular CLI
$ npm install -g @angular/cli
# 创建新的应用程序 RxExample
$ ng new RxExample
$ cd RxExample
$ npm audit fix --force

打开 Intellij IDEA, File / New / Project From Existing Sources...,然后选中工程所在文件夹
在向导的第1页选择 Create project from existing sources
完成向导后在点击 Finish 创建工程。

点击 Add Configurations, 点击 +npm
Name: Angular CLI Server
Scripts: start
点击 OK 完成配置。
点击 Angular CLI Server 启动程序。
http://localhost:4200/ 可打开网页。

AppComponent

打开 app.component.html 文件,将其改为

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<p>
  <input #number1 style="width:50px;text-align:right;" value="1"> +
  <input #number2 style="width:50px;text-align:right;" value="2"> +
  <input #number3 style="width:50px;text-align:right;" value="3"> =
  <label>{{result | async}}</label>
</p>

打开 app.component.ts 文件,将其改为

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { combineLatest, fromEvent, Observable } from 'rxjs';
import { map, pluck, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  @ViewChild('number1') number1: ElementRef;
  @ViewChild('number2') number2: ElementRef;
  @ViewChild('number3') number3: ElementRef;
  result: Observable<string>;

  title = 'RxExample';
  constructor() { }

  ngAfterViewInit() {
    const f = elemRef => fromEvent(elemRef.nativeElement, 'input')
      .pipe(pluck('target', 'value'), startWith((elemRef.nativeElement as HTMLInputElement).value));
    const g = s => Number(s) || 0;
    this.result = combineLatest(f(this.number1), f(this.number2), f(this.number3))
      .pipe(map(results => String(g(results[0]) + g(results[1]) + g(results[2]));
  }
}

ReactiveX 学习笔记(22)使用 RxJS + Angular 进行 GUI 编程

原文:https://www.cnblogs.com/zwvista/p/9574484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!