rxjs - rxjs 和我试图避免的 if-then-else 的不良做法
问题描述
我有一个可观察的 rxjs,我打算只打印一个彩色火车。代码可以在https://codesandbox.io试用
import { from } from "rxjs";
import { merge, filter ,tap,} from "rxjs/operators";
const nextTrain$ = from(['Yellow', 'Neon', 'Amber']);
const yellowTrain$ =
nextTrain$
.pipe(
filter(color => color === 'Yellow'),
tap(console.log(`Yellow Color Train is comming`))
)
const greenTrain$ = nextTrain$
.pipe(
filter((color) => color === 'Green'),
tap(console.log(`Green Color Train is comming`))
)
const blueTrain$ = nextTrain$
.pipe(
filter((color) => color === 'Blue'),
tap(console.log(`Blue Color Train is comming`))
)
merge(yellowTrain$,
greenTrain$,
blueTrain$).subscribe()
我只希望打印黄色火车的声明,但我得到所有三个声明打印任何想法我在这里做错了什么?
同样在附加订阅合并语句的代码框中错误地指出我做错了什么?
解决方案
这是因为tap
使用不正确,您应该传递函数,如下所示:
tap(() => console.log(`Yellow Color Train is comming`))
你写它的方式是不正确的,因为你总是在调用console.log
(因此控制台中的所有消息),但是调用console.log
不返回函数(它们 return undefined
)因为tap
期望一个,所以tap
基本上根本没有工作。
同样在附加订阅合并语句的代码框中错误地指出我做错了什么?
你做错了进口。这是正确的:
import { from, merge } from 'rxjs';
import { filter, tap } from 'rxjs/operators';
这是有关如何进行正确导入的说明。
最后:
import { from, merge } from 'rxjs';
import { filter, tap } from 'rxjs/operators';
const nextTrain$ = from(['Yellow', 'Neon', 'Amber']);
const yellowTrain$ =
nextTrain$
.pipe(
filter(color => color === 'Yellow'),
tap(() => console.log(`Yellow Color Train is comming`))
)
const greenTrain$ = nextTrain$
.pipe(
filter((color) => color === 'Green'),
tap(() => console.log(`Green Color Train is comming`))
)
const blueTrain$ = nextTrain$
.pipe(
filter((color) => color === 'Blue'),
tap(() => console.log(`Blue Color Train is comming`))
)
merge(yellowTrain$,
greenTrain$,
blueTrain$).subscribe();
推荐阅读
- java - ArCore 成功楼层查找
- windows - 为 windows 编译 openexr 时出现 Visual Studio 和 cmake 错误
- node.js - 如何使用 Webpack 为 Rest API Express NodeJS 服务器创建包
- php - PDO 为多个条件返回空
- php - PHP substr 返回少于预期
- delphi - LockBox 3 加密不匹配在线工具,怀疑填充或密钥问题
- windows - BCDEdit 错误,参数不正确
- javascript - Vue将对象复制到本地数据
- c# - Mono.Data.Sqlite 可以与 Xamarin 一起使用吗
- html - 溢出:自动和固定高度使 Microsoft Edge 中的下拉文本模糊