Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngrx Effects: Dispatch Empty Action

Tags:

angular

rxjs

ngrx

How do I get my ngrx/store effect to dispatch an empty action? I'm running Angular 6/rxjs 6:

  @Effect()
  testEffect$ = this.actions$.ofType(FIRST_ACTION).pipe(
    map((x) => {
       if (x === y) {
          return new SECOND_ACTION;
       } else {
          fire.some.effect;
          return EMPTY;
       }
    })
  );

At the moment, I'm getting two errors: Effect "testEffect$" dispatched an invalid action: [object Object] followed by TypeError: Actions must have a type property.

I found this answer, but it doesn't seem to work with ng/rxjs 6. So far, I've tried the following (none work):

EMPTY, Observable.empty(), Observable.of() and Observable.of([]), { type: 'EMPTY_ACTION' }

Any help would be appreciated! I know I can use { dispatch: false }, but the actual effect has about five outcomes and only one of them doesn't use an action, so I'd rather have that last one return something as well.

like image 438
Barruzi Avatar asked Jun 13 '18 09:06

Barruzi


2 Answers

Here is a possible solution:

@Effect()
  testEffect$ = this.actions$.ofType(FIRST_ACTION).pipe(
    tap((x) => { // do some side effect here
        if (x !== y ) {
            fire.some.effect;
        }
    }),
    filter((x) => x === y), // proceed only if condition is true
    map((x) => {
       return new SECOND_ACTION; // then return the needed action
    })
  );
like image 90
Anton Dosov Avatar answered Sep 22 '22 19:09

Anton Dosov


you could just use filter

@Effect()
testEffect$ = this.actions$.ofType(FIRST_ACTION).pipe(
  filter(x => x === y),
  map( x => new SECOND_ACTION)
)

and if you still need the other case you can write another effect with dispatch: false

like image 40
itay oded Avatar answered Sep 22 '22 19:09

itay oded