map
和数组的map类似
const letters = of('a', 'b', 'c');
const result = letters.pipe(
map(x => x + 'map')
);
输出
amap
bmap
cmap
mergeMap
这个操作符可以将两个observable合并
第一个
const letters = of('a', 'b', 'c');
第二个
interval(1000)
通过mergeMap,interval可以获取of操作符的数据,完整代码
import { interval, of } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
const letters = of('a', 'b', 'c');
const result = letters.pipe(
mergeMap(
ofData =>
interval(1000).pipe(
map(dataFromInterval => ofData + dataFromInterval)
)
)
);
输出
a0
b0
c0
a1
b1
c1
a2
b2
c3
...
scan和reduce
这两个几乎一样,scan类似js的forEach,reduce类似js的reduce,接受两个参数,第一个参数function是对接受的当前值和接受的数据,第二个参数speed是传给function当前值的默认值
const obs = of( 'n', 'a', 'm', 't', 'a', 'b');
const result = obs.pipe(
scan((current, accept) => accept + current, '!'),
);
result.subscribe(x => console.log(x));
输出
n!
an!
man!
tman!
atman!
batman!
可以看到scan每次接受值也会输出一次,再看看reduce
const obs = of( 'n', 'a', 'm', 't', 'a', 'b');
const result = obs.pipe(
reduce((current, accept) => accept + current, '!')
);
result.subscribe(x => console.log(x));
输出
batman!
reduce只有一次输出
pluck
该操作符可以按照传入的参数,逐层访问对象
const clicks = fromEvent(document, 'click');
clicks.subscribe(e => console.log(e));
const tagNames = clicks.pipe(pluck('target', 'tagName'));
tagNames.subscribe(x => console.log(x));
比如,这里click事件返回的e对象简化结构
{
target: {
tagName: 'xxx',
...
}
...
}
pluck就先获取e的target,再从target中获取tagName,更直观的例子
const first1 = of(
{ v: 1 },
{ v: 2 },
{ v: 3 },
{ v: 4 },
{ v: 4 },
);
const result = first1.pipe(
pluck('v')
);
result.subscribe(x => console.log(x));
输出
1
2
3
4
4
startWith和endWith
分别在流的最开始和最后插入参数
of("from source")
.pipe(startWith("first", "second"))
.subscribe(x => console.log(x));
of('hi', 'how are you?', 'sorry, I have to go now').pipe(
endWith('goodbye!'),
)
.subscribe(word => console.log(word));
输出
first
second
from source
hi
how are you?
sorry, I have to go now
goodbye!
令人头秃。。。持续更新