Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 816
Hongbo Miao Avatar asked Sep 02 '16 19:09

Hongbo Miao


People also ask

What is effect () in Angular?

​@ngrx/effects provides an Angular actions$ service (which is also an Observable ) to emit every action that has been dispatched by your application in a single stream. Its ofType() method can be used to filter the one or more actions we're interesting in before adding a side-effect.

What are side effects in NgRx?

A side effect refers simply to the modification of some kind of state - for instance: Changing the value of a variable; Writing some data to disk; Enabling or disabling a button in the User Interface.

How do you handle errors in NgRx effects?

To start, the application makes a service call in an effect when the location is updated with a LoadLocations action like you see here: When an error happens, the catchError operator is used, and then of returns an observable with aLocationsError action to update the store.


1 Answers

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 }};
        }
    });
like image 182
André Werlang Avatar answered Nov 15 '22 05:11

André Werlang