前言
在使用 angular 的过程中,rxjs的强大方便毋庸置疑,但是在初学的时候它的各种操作符是真的让人是查的心累。把使用及查到的各种操作符记录下来,方便查找。
过滤符
- startWith: 在开头添加要发送的元素
- filter: 传入function 过滤发送的元素(类似数组 filter)
- scan: 传入function (类似数据reduce 函数第一参数是返回值,第二个值是数据流)
- skip: 传入数字,跳过N个元素
- skipUntil 接收的是 Observable 类型,忽略Observable发出之前的值 (同takeUntil理解)
- skipWhile 接收的是 function ,返回true则过滤,一旦false则后面不过滤 (同takeWhile理解)
- last: 取最后一个元素 (注意放的位置)
- first: 取最后一个元素 (注意放的位置)
- take: 传入数字,只取N个数的元素
- takeUntil 接收的是 Observable 类型,当这个Observable发出值 就complete
- takeWhile 接收的是 function ,一旦返回值为false 就complete
import { from, timer, Subject } from 'rxjs';
import { filter, take, last, startWith, skip } from 'rxjs/operators';
destroy$ = new Subject();
ngOnInit() {
// 发出(1, 2, 3, 4, 5)
const source = from([1, 2, 3, 4, 5]);
const example = source.pipe(
// 开头追加 6, 8 得 6, 8, 1, 2, 3, 4, 5
startWith(6, 8),
// 跳过前两个
skip(2),
// 只取偶数得
filter(num => num % 2 === 0),
// 数据累加
scan((all,item) => all + item),
// 再取前两个值
take(2),
// 只取最后一个值
last(),
// 取x < 3的值,>=3 则example 就处于complate 状态
takeWhile(x => x < 3),
// 取timer事件发出之前的值,发出后example 就处于complate 状态
takeUntil(timer(5000)),
takeUntil(this.destroy$), 通常用于组件销毁时 complate 状态
);
example.subscribe(val => {
console.log(`The number: ${val}`)
});
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complate();
}
防抖节流
- debounce 防抖 会根舍弃掉在两次输出之间小于指定时间的发出值。
- debounceTime: 接收毫秒数,舍弃掉在两次输出之间小于指定时间的发出值(最后一次输入毫秒数之后出发)。
- throttleTime: 接收毫秒数,经过指定的这个时间后发出最新值。
// 防抖
interval(1000).pipe(
// 5秒后,debounce 的时间会大于 interval 的时间,之后所有的值都将被丢弃
debounce(val => timer(val * 200)),
);
fromEvent(this.input.nativeElement, 'input').pipe(
// 两次输入小于1秒忽略 最后一次输入1秒后触发一次
debounceTime(1000)
//首次输入 及连续输入到达2秒返回最新值,最后一次输入距离上次输入不到2秒则不会触发最后一次输入。
throttleTime(2000)
).subscribe( (x: any) => {
console.log('x', x.target.value);
});
后续
暂时就先记这么多,后面还有合并操作符等等,慢慢记。忘了再翻翻!