1. 程式人生 > >Angular Routing Series: Pillar 1 

Angular Routing Series: Pillar 1 

Router States

The result of successfully matching a URL is that some set of components will be routed to, and rendered on screen through the use of router-outlet directives. But there is also a useful side effect to this operation — the creation of RouterState and state snapshot objects.

After routing has occurred, we might want to access information about the URL and the set of components that were routed to— known as the current router state

. The term router state is somewhat overloaded, as the objects inside of the ROUTES array are said to define the possible router states for an application, that is, the sets of components that can be routed to for a particular URL. However, routerState is also a property on the Router Service. In this section, router state
will refer to the routerState property on the Router service, which lets us access information about what URL and components are currently routed to.

For instance, we may need to access query parameters, or other data encoded in the URL from within a component or service. The Router service provides a property called , which lets you access everything about the current state of the router. The routerState

has two properties of interest to us; snapshot, and root.

A snippet of the Router service

Both are trees representing the current router state (components that have been routed to, along with URL segments and parameters), but they differ in one key way, snapshot is a tree of ActivatedRouteSnapshot objects — which are static, root is a tree of ActivatedRoute objects — which are dynamic.

Sometimes a snapshot of state is enough, and other times, you want to subscribe to an observable to listen for state changes.

For example, when a URL changes from /users/15/notes/41 to /users/15/notes/42, the router will recognize that only the :noteid parameter has changed, so it will simply reuse the current set of components on screen, and will not create a new tree of snapshots. In this case, it’s better to use the observable approach, if you know route parameters are likely to change.

Note that a routerState can have multiple trees of ActivatedRoutes at once — one for each outlet.

When we say that the URL is just a serialization of the router state, this is what is meant.