May 12, 2022
Difference between ActivatedRoute and ActivatedRoute Snapshot in Angular
Angular is a TypeScript-based open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS. Angular recommends the use of Microsoft's TypeScript language. TypeScript is a superset of ECMAScript 6 (ES6) and is backward compatible with ECMAScript 5. It supports Angular Universal, a technology that runs your Angular application on the server. It has its own suite of modern UI components that work across the web, mobile, and desktop, called Angular Material.
Here, we explain the difference between ActivatedRoute and ActivatedRouteSnapshot in Angular.
So, let's get started -
It contains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.
It contains the information about a route associated with a component loaded in an outlet. An ActivatedRoute can also be used to traverse the router state tree.
ActivatedRoute vs ActivatedRouteSnapshot
- Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute. It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.
- 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.
- If you use ActivatedRouteSnapshot and have a parameter in your route definition like product/:id, then you will not get any new ID 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.
- ActivatedRouteSnapshot is an immutable data structure.
- ActivatedRouteSnapshot is representing the state of the router at a particular moment in time.
- ActivatedRoute is similar to ActivatedRouteSnapshot, except that it represents the state of the router changing over time.
- Every node in ActivatedRouteSnapshot tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data.
- When using snapshot - doesn't show the right ID when clicking. So your statement here is incorrect.
- Use the Snapshot if you only need the initial value of the parameter once during the component's initialization, and don't expect the URL to change while the user is still on that same component.