Hongbo Miao Hongbo Miao - 3 months ago 58
TypeScript Question

How to do if/else in ngrx/effects?

I am using ngrx/effects. I want to dispatch different actions based on a

foo
state in the store.

This is how I am doing now:

@Effect() foo1$ = this.updates$
.whenAction(Actions.FOO)
.filter(obj => !obj.state.product.foo)
.map<string>(toPayload)
.map(x => ({ type: Actions.BAR1, payload: { x }}));

@Effect() foo2$ = this.updates$
.whenAction(Actions.FOO)
.filter(obj => obj.state.product.foo)
.map<string>(toPayload)
.map(x => ({ type: Actions.BAR2, payload: { x }}));


Is there a way to use RxJS 5 operators like
partition
,
groupBy
,
if
,
case
in this post? I cannot use it correctly now.

Answer

Having 2 separate effect sources are fine. Otherwise make it simple:

@Effect() foo$ = this.updates$
    .whenAction(Actions.FOO)
    .map(({action, state}) => {
        if (state.product.foo) {
            return { type: Actions.CHAT_GET_MESSAGES2, payload: { action.payload }};
        } else {
            return { type: Actions.CHAT_GET_MESSAGES, payload: { action.payload }};
        }
    });