我们什么时候应该使用 RxJS tap 操作符? [英] When should we use the RxJS tap operator?

查看:90
本文介绍了我们什么时候应该使用 RxJS tap 操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白 文档.谁能给我解释一下?

I do not understand from the docs. Could anyone explain it to me?

推荐答案

大多数操作符都是按流式顺序工作的,例如:

Most of the operators are working in streamed sequence, for example:

source$.pipe(
  map((a: string) => changeAndReturnArray(a)),
  filter((b: string[]) => giveMeOnlySymbolsThatAreAfterNInAlphabet(b)),
  switchMap((c: string[]) => putToSomeObservable(c))
  ....
);

在该示例中,您不是破坏"流,也不是跳出它来执行某些外部操作.使用tap"运算符可以跳出流,您可以:

In that example you are not 'breaking' the stream, or jumping outside of it to do some external action. Jumping outside of stream is possible with 'tap' operator, where you can:

  • 调用会导致某些副作用的函数,这可能对最终用户可见(例如 - 显示对话框、显示小吃栏、重定向到不同的路线(但我认为不建议以这种方式使用点击))
  • 商店的调度操作(如果您正在使用任何 - 例如 ngrx 商店)
  • 调试你的代码 -> console.log()
  • 任何可以被视为流的副作用"的东西.

我的个人意见 - 只有在找不到更好的解决方案时才使用tap".跳出流并调用一些副作用可能是双刃剑,尤其是当您处理一些更大的应用程序时.副作用总是更难维护,你可以用无缘无故做魔术的应用程序结束.

My personal opinion - use 'tap' only if you can't find any better solution. Jumping outside of stream and calling some side effect can be double edged sword, especially when your dealing with some bigger application. Side effect are always harder to maintain, and you can finish with application that is doing magic stuff without any reason.

这篇关于我们什么时候应该使用 RxJS tap 操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆