响应式编程包括:
可观察者Observable(流):表示一组值或者事件的集合
观察者Observer:一个回调函数的集合,它知道怎样去监听被Observable发送的值
订阅Subscription:表示一个可观察对象,主要用于取消注册
操作符Operators:纯粹的函数,使开发者可以以函数编程的方式处理集合。
可以通过Observable产生流,首先引入它
Observable.from([1,2,3,6,5])
.filter(e=>e%2==0)
.map(e=>e*2)
.subscribe(
e=>console.log(e),
erro=>console.error(erro),
()=>console.log('结束')
)
在angular中有它本身的编程方式,设置一个搜素框,现在设置一个时间间隔,每次输入完后在进行搜素,实现方式,首先引入ReactiveFormsModule
i
mport{FormsModule,ReactiveFormsModule} from '@angular/forms'
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
控制台加入FormControl
import{FormControl} from '@angular/forms'
export class BindComponent implements OnInit {
searchInput:FormControl =new FormControl();
constructor() {
this.searchInput.valueChanges
.subscribe(stockCode=>this.getStockInfo(stockCode));//stockCode就是用户输入的值
}
getStockInfo(value:string){
console.log(value);
}
ngOnInit() {
}
}
input标签
<input [formControl]="searchInput">
加入时间间隔需要引入rxjs
import {Component, OnInit} from '@angular/core';
import{FormControl} from '@angular/forms'
import 'rxjs/Rx'
@Component({
selector: 'app-bind',
templateUrl: './bind.component.html',
styleUrls: ['./bind.component.css']
})
export class BindComponent implements OnInit {
searchInput:FormControl =new FormControl();
constructor() {
this.searchInput.valueChanges
.debounceTime(500)//设置为500毫秒
.subscribe(stockCode=>this.getStockInfo(stockCode));
}
getStockInfo(value:string){
console.log(value);
}
ngOnInit() {
}
}