Keep data in the state object during navigation in Angular

Wojciech Trawiński
JavaScript everyday
2 min readFeb 4, 2019

--

Have you ever been in need of passing some extra data during navigation in Angular? If so, you must have used either a dedicated service or query parameters to handle the problem. However, there has been a far more elegant tool available since the release of Angular 7.2, namely the state object.

In this post I’ll present an example from a real-world application wherein the new feature would be extremely useful.

Problem description

If the access to your application’s content is restricted to authenticated users, you probably has an auth guard applied to each route except for the auth page.

Moreover, the auth guard should check if a user is authenticated and redirect unauthenticated users to the auth page.

Passing data

With the aid of the state object you can pass some extra data like a redirect url, namely the route url that a user wanted to activate.

Note that you can get a desired url based on the injected instance of RouterStateSnapshot.

The state object is defined as a property of the NavigationExtras object passed as the second argument to the navigate or navigateByUrl router’s methods. In addition, you can make use of an attribute directive ([state]=”state object”) if you rely on declarative navigation in your application.

Reading data

Once a user has successfully authenticated, you should navigate to the requested page. The redirect url has been persisted with the aid of the state object. Let’s see how you can read the data.

The state object is present under the state property of the window’s history object. In addition, you should take into account that a user may refresh your application when being on the auth page. As a result, the state won’t be set and you need to provide a fallback redirect url (in the above example it’s just ‘/’).

Conclusions

The state object is a very handy addition to the extremely powerful Angular’s Router. I’ve been in need of passing some data during navigation in the following situations:

  • persisting a redirect url,
  • navigation to the error page with an error’s code, so that a proper message could be obtained based on a code-message dictionary.

In the first situation I kept the redirect url within the auth service, whereas in the second one I relied on a query parameter to pass an error’s code. Although I didn’t have any troubles in tackling the aforementioned problems, using the state object seems a better and more elegant solution.

--

--