首页 > 解决方案 > RXJS 管道中未触发 tap()

问题描述

我必须做同样的事情的方法,虽然我更喜欢第一个。但是第一种方法似乎不起作用。(tap()未触发)

// does not work
this.actions$.pipe(
    ofType(LayoutActions.Types.CHANGE_THEME),
    takeUntil(this.destroyed$),
    tap(() => {
        console.log('test')
    }),
);
// works
this.actions$.ofType(LayoutActions.Types.CHANGE_THEME).subscribe(() => {
    console.log('test')
});

标签: angularrxjsreactive-programmingngrx

解决方案


想象一下 RxJS 管道就像实际的物理管道,末端有一个阀门。每条管道都会“改变”流过它的液体,但只要末端的阀门关闭,就不会有任何东西流动。

所以,你需要的是在最后打开阀门。这是通过订阅可观察管道来完成的。最简单的解决方案是:

this.actions$.pipe(
    ofType(LayoutActions.Types.CHANGE_THEME),
    takeUntil(this.destroyed$),
    tap(() => {
        console.log('test')
    }),
).subscribe(_ => console.log("water is flowing!"));

推荐阅读