Angular ActivatedRoute vs ActivatedRouteSnapshot

This snapshot will never change. © 2012 Jared Youtsey

When would you use one over the other?


Volatile state, use ActivatedRoute.
Static state, use ActivatedRouteSnapshot.


Login is a good example of when to use ActivatedRouteSnapshot. When you go to the login page, there isn't anything you would change on the login page that would cause some other part of the page to need to reload. It's static. Most forms are fairly static routes. If they need to access the route params, use ActivatedRouteSnapshot. A clue to this might be a route that does not have a parameter defined on it such as product/:id.

A route defined with product/:id will almost certainly want to use ActivatedRoute. Or, perhaps you have a page that has some global filters on it that you want all child components to respond to when those filters change. That's a good candidate for ActivatedRoute if you are going to store the filter state in the route (which you might want if you want to email the filter to a friend).

Pro’s and Con’s

ActivatedRoute requires that you subscribe. Which requires that you unsubscribe. Which requires that you implement OnDestroy. This is a lot of overhead for a static route.

However, if you use ActivatedRouteSnapshot and have a parameter in your route definition like product/:id, then you will not get any new id's if the user changes them or your page does. Snapshot means that it was when OnInit ran, this was the state it was in at that point in time. So, any changes will be ignored.

How To

You still have to import ActivatedRoute in your constructor:

export class MyClass {
private route: ActivatedRouteSnapshot;

constructor(activatedRoute: ActivatedRoute) {
this.route = activatedRoute.snapshot;

But, now, you don’t have to do all of the subscribe/unsubscribe.