ReactiveX 學習筆記(22)使用 RxJS + Angular 進行 GUI 編程
阿新 • • 發佈:2018-09-02
ons ref code aud types 啟動 syn 筆記 div
在向導的第1頁選擇 Create project from existing sources
完成向導後在點擊 Finish 創建工程。
課題
- 程序界面由3個文本編輯框和1個文本標簽組成。
- 要求文本標簽實時顯示3個文本編輯框所輸入的數字之和。
- 文本編輯框輸入的不是合法數字時,將其值視為0。
- 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...,然後選中工程所在文件夾
完成向導後在點擊 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 編程