常用操作符
本地使用环境为rollup+rxjs,具体的rollup配置,请参考另一篇文章,这里不再赘述。
import { of,Observable, interval,Subject ,from,bindCallback} from 'rxjs';
import { version } from './package.json';
import { ajax } from 'rxjs/ajax';
import { map, catchError } from 'rxjs/operators';
const someFunction = (a, b, c) => {
console.log("a"); // 5
console.log("b"); // 'some string'
console.log("c"); // {someProperty: 'someValue'}
};
const boundSomeFunction = bindCallback(someFunction);
boundSomeFunction().subscribe(values => {
console.log(values) // [5, 'some string', {someProperty: 'someValue'}]
});
from
//逐行输出 1,2,3
import { from} from 'rxjs';
const arr = [1,2,3];
const result$ = from(arr);
result$.subscribe(res => console.log(res));
range
//逐行输出 1-10
import { range } from 'rxjs';
const numbers = range(1, 10);
numbers.subscribe(x => console.log(x));
timer
//1 ....
import { timer } from 'rxjs';
const numbers = timer(3000,1000); //延迟3s,定时1s
numbers.subscribe(x => console.log(x+1));
interval
// 1....
import { interval } from 'rxjs';
const numbers = interval(1000);
numbers.subscribe(x => console.log(x+1));
of
// 输出数组 [1,2,3]
import { of } from "rxjs";
const arr = [1,2,3]
const result$ = of(arr);
result$.subscribe(res => console.log(res));
// 逐行1,2,3
const result$ = of(1,2,3);
result$.subscribe(res => console.log(res));
条件判断
import { defer, fromEvent, interval,of } from 'rxjs';
const clicksOrInterval = defer(() => { //es6 支持
return Math.random() > 0
? of('click')
: interval(1000);
});
clicksOrInterval.subscribe(x => console.log(x));
import { defer, fromEvent, interval,of, iif } from 'rxjs';
let isFisrt;
const clicksOrInterval = iif(
() => isFisrt,
of('first'),
of('second')
);
isFisrt = true;
clicksOrInterval.subscribe(x => console.log(x));
isFisrt = false;
clicksOrInterval.subscribe(x => console.log(x));
延迟
import { fromEvent ,of} from 'rxjs';
import { delay } from 'rxjs/operators';
const res = of(1,2,3);
const delayedClicks = res.pipe(delay(1000)); // each click emitted after 1 second
delayedClicks.subscribe(x => console.log(x));
防抖
import { fromEvent } from 'rxjs';
import { throttle } from 'rxjs/operators';
const clicks = fromEvent(document, 'click');
const result = clicks.pipe(throttle(ev => interval(1000)));
result.subscribe(x => console.log(x));
map
import { of} from 'rxjs';
import { delay,map} from 'rxjs/operators'; //注意map引入
const res = of(1,2,3);
const delayedClicks = res.pipe(map(item => item * 2)); // each click emitted after 1 second
delayedClicks.subscribe(x => console.log(x));
filter
import { of} from 'rxjs';
import { delay,filter} from 'rxjs/operators';
const res = of(1,2,3);
const delayedClicks = res.pipe(filter(item => item % 2 === 0)); // each click emitted after 1 second
delayedClicks.subscribe(x => console.log(x));
本文作者:前端首席体验师(CheongHu)