JSON
JSON

Reputation: 1623

How can I get activated route when navigation in effect module using the router store?

I am trying to dispatch the router store navigation action relative to the component route. the trace log for routing shows that the relative path taken for navigation is the app-path instead of the component path.

 return of(
        new routerActions.Go({
          path: ['./', payload.rootPath],
          extras: { relativeTo: this.route },
        }),
      );

 constructor(
    private actions$: Actions,
    private route: ActivatedRoute,
  ) {}

I am injecting the ActivatedRoute in my effect module constructor which seems the issue here. How can I get the activated route outside of my component and pass it to the navigation action?

Upvotes: 2

Views: 4220

Answers (2)

Passing activatedRoute didn't work for me. This is what I did. The selector selectRouterUrl selects the current URL from the state.

  navigateRelative$ = createEffect(() => this.actions$.pipe(
    ofType(navigateRelativeTo),
    withLatestFrom(this.store.select(selectRouterUrl)),
    tap(([{ commands }, url]) => this.router.navigate([url, ...commands])),
  ), { dispatch: false });

Upvotes: 1

Eric S
Eric S

Reputation: 157

ActivatedRoute is specific to each routed component.

This gives you a couple options.

  1. Navigates the root route to return the data you need.

let route = this.router.routerState.root;
while (route.firstChild) {
route = route.firstChild;
}

return route.snapshot;

  1. Pass the ActivatedRoute from the routed component in the package.

  constructor(private store: Store<AppState>, private activatedRoute:ActivatedRoute) {}

  doSomething() {
    this.store.dispatch(new Action.YourAction({ id: actionId, route: activatedRoute });
  }
  
 

Upvotes: 7

Related Questions