可观察对象在input中的使用

使用场景:

根据input输入内容,实时查询api接口。

 

思路流程:

通常对于输入内容做以下一系列操作:

1.监听input输入值;

2.去除输入值两端空格键,判断是否满足最小输入长度;

3.debounce.即不是在每次击键时发送api请求,而是等待击键的中断;

4.输入值相同时不发送api请求;

5如果更新后的结果无效,则取消正在进行的ajax请求;

 

例子:

import { fromEvent } from 'rxjs';

import { ajax } from 'rxjs/ajax';

import { map, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

const searchBox = document.getElementById('search-box');

const typehead = fromEvent(searchBox, 'input').pipe(

  map((e: KeyboardEvent) => e.target.value),

  filter(text => text.length > 2),

  debounceTime(10),

  distinctUntilChanged(),

  switchMap(() => ajax('/api/endpoint'))

);

typehead.subscribe(

  data => {

    //handle the data from the api

  }

);

 

原文及参考:

angular.io/guide/practical-observable-usage

rxjs-dev.firebaseapp.com/api/operators/switchMap

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值