我阅读了文章中的不同之处,但要点如下。
所以tap我可以改变变量,比如如果我把x=3+4它改变了变量的值,那么我可以说有一个副作用。
但是map我可以改变循环每个值的值,不是吗?你能指出他们有哪些突出的差异吗?
轻敲
RxJS tap 对源 Observable 发出的每个值执行副作用,并返回与源 Observable 相同的 Observable,直到没有错误为止。
地图
map 是一个 RxJS 可管道操作符。map 将给定的函数应用于源 Observable 发出的每个元素,并将结果值作为 Observable 发出
cus*_*der 29
映射函数接受一个事物并返回另一个事物。例如,我可以构建一个接受10和返回11、接受11和返回12等的函数。
const inc = n => n + 1;
Run Code Online (Sandbox Code Playgroud)
Array#map 将这种映射函数应用于数组的所有元素,但“映射”并不意味着“迭代”。
在 RxJS 中,当数据被发送到流时,它会通过一系列操作符:
map运营商将简单地套用一个函数的数据并返回结果。tap然而,操作符获取一个数据,将一个函数应用于该数据但返回原始数据,如果该函数不屑于返回结果,则tap忽略它。下面是一个例子:
10送到 stream a$,tap只记录值。我们知道它console.log总是返回,undefined但这很好,因为它tap只是返回它的参数。10送到流b$,它通过map(inc)它适用inc于10返回11。const inc = n => n + 1;
Run Code Online (Sandbox Code Playgroud)
const a$ = of(10).pipe(tap(n => console.log(`tap: ${n}`)));
const b$ = of(10).pipe(map(inc));
a$.subscribe(n => console.log(`n from a$: ${n}`));
b$.subscribe(n => console.log(`n from b$: ${n}`));Run Code Online (Sandbox Code Playgroud)
Lux*_*lem 14
Tap应该用于通知,记录非上下文/关键副作用。
这就像“窥视”“管道”。数据保持不变,你可以用它做一些事情。一些数据进去,你看,同样的数据出来。
Map用于转换/映射“管道”中的数据。一些数据进来,不同/转换的数据出来。
的tap和map都是RxJS运营商,运营商RxJS只是函数执行一些处理过的数据。
它们都pipeable operators将输入作为 Observable,执行一些操作并返回输出 observable。
地图和水龙头的区别:
的map是操作者pipeable接受一个输入观察的,执行它的一些操作并返回一个新的操纵观察到。例如
const source$ = of(1,2,3) // observable which will emit 1,2,3
// It take an input observable and return a new observable which will emit square of input values.
// So, the output observable will emit 1,4,9
const mapSource$ = of(1,2,3)
.pipe(map(value => value * value))
Run Code Online (Sandbox Code Playgroud)
tap另一方面,操作符接受一个输入 observable 执行一些操作并返回相同的输入 observable。
const source$ = of(1,2,3) // observable which will emit 1,2,3
// It take an input observable and return a same observable after console value.
// So, the output observable will emit 1,2,3
const tapSource$ = of(1,2,3)
.pipe(tap(value => console.log(value)))
Run Code Online (Sandbox Code Playgroud)
小智 7
的目的tap是执行一个保持可观察值相同的动作
的目的map是转换observable 的发射值
const messagesCount$ = newMessages$
.pipe(tap(messages => notificationService.notify('You have ' + message.length + ' message(s)')))
.pipe(map(messages => messages.length))
Run Code Online (Sandbox Code Playgroud)
您可以将tap运算符视为 void 函数,无论它对输入值执行什么操作,都不会更改原始值
const source = of(1, 2, 3, 4, 5);
// here we are manipulating the input value but the output value of the observable still the same
const example = source.pipe(
tap(val => val + 100),
);
// output: 1, 2, 3, 4, 5
const subscribe = example.subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我们使用map运算符对可观察的输入值进行任何操作,它将改变输出值
const example = source.pipe(
map(val => val + 100)
);
// output: 101, 102, 103, 104, 105
const subscribe = example.subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17939 次 |
| 最近记录: |