Let’s inspect how can we access router parameters in angular. In order to get access to route parameters we need to inject the ActivatedRoute class in our component or service constructor.
This class is defined in “@angular/router” which is defined in RouterModule
With this initial setup in ngOnInit we can get the route parameter from this object.
route.paramMap is the property that give us all the parameters in this route.
The type of this property is Observable<ParamMap>.
As with all Observable we call call subscribe method to subscribe and get values emitted in this observable. Here we need to pass to subscribe a function that takes a ParamMap and returns void (value: ParamMap) => void
In order to get the value of the id parameter we call the get method like this:
the get method returns a string, if what we need is to work with integers we simple add a + sign like this:
This is the way you can access parameters. The first question I had when I first worked with route parameters was why route parameters are Observables, that makes more difficult to get and work with parameters isn’t?
Well it turns out that there is a very good reason for this. This has to be with what happens when navigating from component to component. When navigating from component1 to component2 angular destroys component1 entirely. Now imagine the scenario where all our functionality is in the same controller and we need to change the route information and navigate into internal components but without destroying and recreating current working component, this is in fact the reason why route parameters are defined as observables, to allow users to stay on the same page and navigate back and forth.
In cases where is not necessary to let the user stay on the same page and navigate back and forth, we can use a simpler way to get access to route parameters. This simpler way is by using route snapshots like this.
In the next blog post I’ll review the best way to work with multiple route parameters in angular.