I need to update my ngxs state depending on different navigation routs, but when I use
constructor(private route: ActivatedRoute) {}
in the constructor in the state and try to use it inside the action I get empty params.
I can pass the route as a payload when dispatching a function, but I doubt if it's a good idea to dispatch the same function inside ngOninit of every routing component.
I installed ngxs/router-plugin, but have no idea how to get the route from it. I was searching on youtube tutorials and modest documentation with no result.
Please help
CodePudding user response:
Let's understand your questions
- Should inject the router into Ngrx store
You should not inject the router into the store. Only mutate the store by dispatching the actions. Use payload to send the data with actions.
- I doubt if it's a good idea to dispatch the same function inside ngOninit of every routing component
There is nothing wrong in dispatching the same actions into multiple components but for your case using the route resolver would be a good choice.
i.g.
//route
[{
path: '/any-path',
component: ContainerComponent,
resolve: {
store: PathResolver
}
}]
//path-resolver.ts
@Injectable({
providedIn: 'root',
})
export class PathResolver implements Resolve<number> {
constructor(private store: Store) {
}
public resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
this.store.dispatch(LoadMyRoute());
// You can pass some data to next components as well
return this.store.pipe(
select(dataForMyRoute),
filter(data => !!data), // <- waiting until data is present
take(1), // <- important to add
);
}
}
Retrieve data into component
constructor(
protected readonly store: Store,
protected readonly activatedRoute: ActivatedRoute,
) {}
public ngOnInit(): void {
this.activatedRoute.data.subscribe(data => {
// everything is here.
});
}
I hope this clarify your questions