What is the difference between ActivatedRouteSnapshot
and ActivatedRoute
in Angular 4? It's my understanding that ActivatedRouteSnapshot
is a child of ActivatedRoute
, meaning that ActivatedRoute
contains ActivatedRouteSnapshot
.
Incidentally, I tried running a Google search for an answer to this question, but I didn't find any of the search results to be understandable.
Thank you!
Since
ActivatedRoute
can be reused,ActivatedRouteSnapshot
is an immutable object representing a particular version ofActivatedRoute
. It exposes all the same properties asActivatedRoute
as plain values, whileActivatedRoute
exposes them as observables.Here is the comment in the implementation:
If a router reuses a component and doesn't create a new activated route, you will have two versions of
ActivatedRouteSnapshot
for the sameActivatedRoute
. Suppose you have the following routing configuration:Now you navigate to:
You will have the param in the
activatedRoute.snapshot.params.id
as1
.Now you navigate to:
You will have the param in the
activatedRoute.snapshot.params.id
as2
.You can see it by implementing the following:
There are 2 ways to get the parameter from the route.
1. Snapshot (
route.snapshot.paramMap.get
). Read it during ctor.Use the Snapshot if you only need the initial value of the parameter once during the component's constructor/init, and don't expect the URL to change while the user is still on that same component.
2. Observable (
route.paramMap.subscribe
). Subscribe to it during ctor.Use the Observable if it's possible for the route to change while the user is still on the same component, and hence the Component's constructor/init would not be called again, but the observable would call your subscribed logic when the URL changed.