
image.png
var subscription = Observable.from([1,2,3,4])
.filter((e) => e%2 == 0)
.map((e) => e*e)
.subscribe(
e => console.log(e),
error => console.error(error),
() => console.log('結(jié)束啦')
);
- 可觀察對(duì)象Observable(流):表示一組值或者事件的集合,
如:
一組值:Observable.from([1,2,3,4]) 中的 [1,2,3,4],
事件:var button = document.querySelector('button');
Observable.fromEvent(button, 'click')
- 觀察者Observer:一個(gè)回調(diào)函數(shù)集合,它知道怎樣去監(jiān)聽被Observable發(fā)送的值,
如:
e => console.log(e),
error => console.error(error),
() => console.log('結(jié)束啦')
- 訂閱Subscription:表示一個(gè)可觀察對(duì)象,主要用于取消注冊(cè)(subscription.unsubscribe()),
這個(gè)是Observable 調(diào)用 subscribe 方法所返回的對(duì)象subscription
- 操作符Operators:純粹的函數(shù),使開發(fā)者可以以函數(shù)編程的方式處理集合,
如:
filter、map等函數(shù)
app.module.ts:導(dǎo)入響應(yīng)式編程需要的模塊ReactiveFormsModule
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
imports: [
FormsModule,
ReactiveFormsModule
],
界面:
<input [formControl]= "inputSearch"/>
.ts文件:
import { Component, OnInit } from '@angular/core';
import {FormControl} from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
// import 'rxjs/Rx'; 在黑白單中,不能這樣導(dǎo)入,應(yīng)該導(dǎo)入需要使用的 子模塊,例如debounceTime子模塊
/*
在tslint.json中,導(dǎo)入黑名單 import-blacklist;rxjs和rxjs/Rx被列入黑名單
"import-blacklist": [
true,
"rxjs",
"rxjs/Rx"
], */
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
inputSearch: FormControl = new FormControl();
constructor() {
this.inputSearch.valueChanges
.debounceTime(500)
.subscribe(
stockCode => this.getStock(stockCode)
);
}
ngOnInit() {
}
getStock(val: string) {
console.log(val);
}
}