Search code examples
angularngrxangular-routingngrx-router-store

How to access a custom serializer when handling ngrx router default actions


I'm using a custom serializer with @ngrx/router-store

export interface CustomSerializer {
  url: string;
  params: Params;
  queryParams: Params;
  data: Data;
  showFilter: boolean;
}

I've done the basic setup and the store is tracking my routes using the serializer type as expected.

I'd like to be able to access the custom type in an effect which triggers from built-in actions, like this

test$ = createEffect(() =>
  this.actions$.pipe(
    ofType(routerNavigatedAction),
    tap(({ payload }) => {
      console.log('filter?:' + payload.routerState.showFilter); <-- not allowed by typescript
    })
  ), { dispatch: false }
);

but payload which is provided by routerNavigatedAction is of type RouterNavigatedPayload<SerializedRouterStateSnapshot>. SerializedRouterStateSnapshot only knows about root and url and knows nothing of showFilter, even though it's there at runtime

debugging breakpoint

(debugging breakpoint before tap()):

Is there a way for me to tie in to the core routing events and configure the infrastructure to return my custom serializer type? If not, is there a 'good' way to get at that showFilter property in my effect? I know I can use a selector to get the data strongly typed from the store, but I would prefer to use the payload which is already provided by the effect.


Solution

  • I think this what you are looking for

    test$ = createEffect(() =>
      this.actions$.pipe(
        ofType<RouterNavigatedAction<CustomSerializer>>(routerNavigatedAction),
        tap(({ payload }) => {
          console.log('filter?:' + payload.routerState.showFilter);
        })
      ), { dispatch: false }
    );