首页 > 解决方案 > 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()

我只希望打印黄色火车的声明,但我得到所有三个声明打印任何想法我在这里做错了什么?

同样在附加订阅合并语句的代码框中错误地指出我做错了什么?

标签: rxjs

解决方案


这是因为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();

推荐阅读