Router DIY — May I go there?

Ran Wahle
2 min readJun 10, 2019

--

We are there, after knowing how to use the router data now is the time to determine if we can actually go to a specific route. In this post I will demonstrate how to implement a canActivate method as it works in Angular router.

Consider the following async arrow function, that returns a promise of boolean.

Our router function should use this guard to check whether we can go to the URL or not. Let’s see how it fits the router configuration

So, our implementation should, before going to the URL, check if the image exists on the server, and only if it exists, go there. The same code can support restricted areas in our application, areas for authenticated users, etc.

Navigate function, with addition

The following navigate function, now turned to eb an async one, has new addition.

have a look at line 11, the function calls another function, canGoOn which calls the guard mentioned above. Let’s see the canGoOn implementation, which is a real simple one

Note: The canGoOn method can return true if no guard exists, or the asynchronously return the guard result.

What about when the user changes the URL?

Well, actually, when the user writes the URL on his own, it goes straight to the history, and therefore we need to have our guard checks when handling the popstate event. On our implementation, we handle it on the router-outlet, the component that will, eventually, render the component targeted on the route data.

Now, because the “wrong” url has gone into the history, all we can do is go one step back.

Let’s wrap

The last step we need to implement, to make our router a perfect one, is to enable the router configuration to have a function that determines whether we may go to a certain URL or not. This is where our guard comes in handy.

If the route is “wrong”, we may prevent it of entering our history object, in case the user has done something on our app, and operated the router.navigate function, and if it came from outside our app (address bar, external link, etc.) we can only go one step back, or have our guard redirecting us elsewhere.

Next: what about navigate away?

--

--