How to bring NavigationExtras to the store with NgRx-router-store?

654 Views Asked by At

I want to save the state of NavigationExtras Information of the navigation call into store. I try to use NgRx router-store for that.

I created a RouterStateSerializer, but i can't get access to the NavigationExtras data from here. The actual solution stores the state in the following navigation (because i use history.state).

Does anybody has an idea how to solve this?

export interface IRouterStateUrl {
  url: string;
  params: any;
  state: any;
}

export class AppRouterStateSerializer implements RouterStateSerializer<IRouterStateUrl> {

  serialize(routerState: RouterStateSnapshot): IRouterStateUrl {
    const {url} = routerState;
    const params = routerState.root.firstChild ? routerState.root.firstChild.params : {};
    const state = history.state;

    return {
      url,
      params,
      state
    };
  }
}

Expect to find the navigation_extra data in the store.

1

There are 1 best solutions below

0
On

was looking for an answer to this problem myself.

I found out a solution: first, you need to add the @Injectable() decorator to your AppRouterStateSerializer class, then you can inject the Router into your serializer. In the end, you can add the extra property to your IRouterStateUrl and return { url, params, queryParams, extras: this.router.getCurrentNavigation()?.extras || {} } from your serializer.

Resulting class

export interface IRouterStateUrl {
  url: string;
  params: Params;
  queryParams: Params;
  extras: NavigationExtras;
}

@Injectable()
export class AppRouterStateSerializer implements RouterStateSerializer<IRouterStateUrl> {
  constructor(private router: Router) {}

  serialize(routerState: RouterStateSnapshot): RouterStateUrl {
    let route: ActivatedRouteSnapshot = routerState.root;

    while (route.firstChild) {
      route = route.firstChild;
    }

    const {
      url,
      root: { queryParams },
    } = routerState;
    const { params } = route;

    // Only return an object including the URL, params and query params
    // instead of the entire snapshot
    return { url, params, queryParams, extras: this.router.getCurrentNavigation()?.extras || {} };
  }
}