Michael Sorens
Michael Sorens

Reputation: 36738

How to make actions known when using ngrx-effects oftype operator

My code base is heavily using ngrx-effects and we use ofType like this:

  @Effect()
  someEffect$ = this.actions$
    .ofType<LoginAction>(UserActions.LOGIN)
  . . .

I recall reading some time back--but cannot find the reference--that ngrx effects no longer needs both the generic type instantiator and the action argument. Checking the docs, I find this example on the v7 Update Guide:

  @Effect()
  someEffect$ = this.actions$
    .ofType(UserActions.LOGIN)
  . . .

That is, it is using the non-generic flavor of ofType.

Now on the ofType docs page itself, it seems to affirm my recollection that both are not needed, stating:

For backwards compatibility, when one passes a single type argument ofType<T>('something') the result is an Observable<T>. Note, that T completely overrides any possible inference from 'something'. Unfortunately, for unknown 'actions: Actions' these types will produce 'Observable'. In such cases one has to manually set the generic type like actions.ofType('add').

Now here's my actual bit of code:

    @Effect()
    toggleTokenFailure$ = this.actions$.pipe(  
      ofType<ToggleTokenActiveFailure>(ApiTokenActionTypes.TOGGLE_FAILURE),
      map(({ payload: { error } }) => new CreateNotification({
      . . .

If I change the ofType line to this:

    ofType(ApiTokenActionTypes.TOGGLE_FAILURE),

the code still works, but I lose my typing on payload (it becomes any). With the original line, the type of payload was HttpErrorResponse (because that is the type of ToggleTokenActiveFailure.payload).

So, per the docs I quoted above, why is my action "unknown", or more to the point, how do I make it known?

Upvotes: 0

Views: 660

Answers (1)

Paweł Jacewicz
Paweł Jacewicz

Reputation: 144

In order to make those types known you have to either provide use ofType<YourAction>(...), just like you did before or provide it to Actions in your constructor. In this case, it could look like that:

type SomeActionsType = ToggleTokenActiveFailure | OtherAction;

@Injectable()
export class SomeEffects {
  constructor(private actions$: Actions<SomeActionsType>) {}

  . . .

  @Effect()
  toggleTokenFailure$ = this.actions$.pipe(  
    ofType(ApiTokenActionTypes.TOGGLE_FAILURE),
    map(({ payload: { error } }) => new CreateNotification({
    . . .
}

Upvotes: 0

Related Questions