1. 程式人生 > >angular2響應式程式設計流

angular2響應式程式設計流

響應式程式設計:
就是非同步資料流程式設計,例如一個單機的事件就是一個流。
是以觀察者模式為核心的,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);
}