Can you explain the difference between ActivatedRoute and RouterState?

26 May 23

Angular

In Angular, ActivatedRoute and RouterState are both key classes related to the router service, but they serve different purposes and provide different levels of information about the current navigation state:

  1. ActivatedRoute: This is a service that's provided to each router component that contains route-specific information such as route parameters, static data, resolve data, global query params and global fragment. You can think of it as the component's window into the current route.

    Here's an example of how you might use ActivatedRoute to access route parameters:

    constructor(private route: ActivatedRoute) { this.route.params.subscribe(params => { console.log(params['id']); // Log the value of the id parameter for this route. }); }
  2. RouterState: On the other hand, RouterState is a tree-structured state that represents the state of the router at a moment in time. It includes all activated routes in the form of a tree and has the information about the entire routing tree, not just the current route.

    The RouterState can be accessed from Router service:

    constructor(private router: Router) { const routerState: RouterState = router.routerState; console.log(routerState.snapshot); // Log the snapshot of the current router state. }

In summary, ActivatedRoute is more focused and local—it represents the state of the current route associated with a component, whereas RouterState is global—it represents the overall state of the router, which could include multiple activated routes in a complex navigation hierarchy.

Frontend development