# 安装 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/ 可打开网页。
打开 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