What is the motivation behind manually creating a stream of route changes instead of using the built in @angular/router's ActivatedRoute as the Angular guide suggests?
export class HeroListComponent implements OnInit {
heroes$: Observable<Hero[]>;
private selectedId: number;
constructor(
private service: HeroService,
private route: ActivatedRoute
) {}
ngOnInit() {
this.heroes$ = this.route.paramMap
.switchMap((params: ParamMap) => {
// (+) before `params.get()` turns the string into a number
this.selectedId = +params.get('id');
return this.service.getHeroes();
});
}
}
For a couple of months, I have jumped on different projects and seen developers control the route changes via creating a stream of route changes and normally you would see something like:
this.route_sub$ = this.route$
.filter((value) => value.params.hasOwnProperty('id') && value.params.hasOwnProperty('date_id'))
.subscribe((value) => {
this.store.dispatch(SomethingEventActions.view({ id: value.params.id }));
I normally recieve a reply saying:
route changes are state changes, so should be handled by state management
Thoughts?
Route changes are state changes, but I would recommend using the @ngrx/router-store instead of subscribing to route and dispatching actions to update state like in your last code snippet.
With @ngrx/router-store you define a Router State Serializer that only return what you need from the RouterStateSnapshot
(RouterStateSnapshot
is a complex structure containing way more than is usually necessary). This is set on state each each time a route navigation actions happens.
This way you can subscribe directly to the router state instead of having to subscribe to route params and THEN update you state (by dispatching an action).
This way, all router state is handled by the serializer and is accessible by all components from state.
In your example you would have to duplicate the subscription and the dispatching of the action in every component that required access to the route.