在使用 angular 的过程当中,rxjs的强大方便毋庸置疑,可是在初学的时候它的各类操做符是真的让人是查的心累。把使用及查到的各类操做符记录下来,方便查找。数组
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();
}
复制代码
// 防抖
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);
});
复制代码
暂时就先记这么多,后面还有合并操做符等等,慢慢记。忘了再翻翻!bash