angular响应式编程

angular依赖一个rxjs的响应式编程的包,所以可以在angular中使用rxjs的所有功能。

响应式编程包括:
可观察者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

import{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() {
  }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值