angular--觀察者模式與rxjs

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);
  }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容