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('结束啦')
);

- 可观察对象Observable(流):表示一组值或者事件的集合,
    如:
        一组值:Observable.from([1,2,3,4]) 中的 [1,2,3,4],
        事件:var button = document.querySelector('button');
        Observable.fromEvent(button, 'click')

- 观察者Observer:一个回调函数集合,它知道怎样去监听被Observable发送的值,
    如:
      e => console.log(e),
      error => console.error(error),
      () => console.log('结束啦')

- 订阅Subscription:表示一个可观察对象,主要用于取消注册(subscription.unsubscribe()),
  这个是Observable 调用 subscribe 方法所返回的对象subscription 

- 操作符Operators:纯粹的函数,使开发者可以以函数编程的方式处理集合,
    如:
      filter、map等函数

app.module.ts:导入响应式编程需要的模块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'; 在黑白单中,不能这样导入,应该导入需要使用的 子模块,例如debounceTime子模块
/*
在tslint.json中,导入黑名单 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);
  }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容