angular2响应式编程流

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiagh/article/details/78218168

响应式编程:
就是异步数据流编程,例如一个单机的事件就是一个流。
是以观察者模式为核心的,rxjs概念
什么是观察者模式?
有两个对象,一个是可观察对象(Observable流),一个是观察者。
先在可观察对象内部注册一些观察者对象,如果可观察对象内部发生了变化的时候,他就会调用观察者中的一些方法,作出一变化。

var subscription =  Observable.from([1,2,3,4])//from是自带的方法会帮你创建一个流,还有fromEvent事件,fromPromise异常,fromEventPattern等
    .filter(e => e%2 ==0)//filter过滤条件
        .map(e => e*e)//得到求平方的流
        .subscribe(//订阅然后作出处理方法
            e => console.log(e),//观察者
            error => console.errorerror),//观察者
            () =>console.log("结束了")//观察者
        );

取消关注

subscription.unsubscribe();
//html代码:

<input [FormControl]='seacrhInput'>//如果input的值有改变的时候,ts文件里的seacrhInput就会调用他的valueChanges方法,将数据存到流里面去。

//ts代码:

import { Component, OnInit } from '@angular/core';
import{ Observable } from 'rxjs';

@Component({
  selector: 'app-my-goods',
  templateUrl: './my-goods.component.html',
  styleUrls: ['./my-goods.component.css']
})
export class MyGoodsComponent implements OnInit {
  public seacrhInput:FormControl = new FormControl();
  constructor() {
   this.seacrhInput.valueChanges
        .debounceTime(500)//500毫秒没有操作的时候就有下面的订阅处理数据
       .subscribe(e => this.getValue(e))
 }

  ngOnInit() {
  }
  getValue(a){
    console.log(a)
    }
}
html:
<input (keyup)='key($event)'>
ts:
key(event){
  console.log(event.target.value);//会输出input的输出值
}
html:
<input #name (keyup) = 'key(name.value)'>
ts:
key(name:string){
  console.log(name);
}

猜你喜欢

转载自blog.csdn.net/xiagh/article/details/78218168