Router DIY — May I go from there?

Ran Wahle
2 min readJun 16, 2019

--

After implementing a what is in angular terminology, a guard, to check whether the user may go to a certain route, we need to implement an opposite one, to determine whether the user may navigate out of a route. This usually comes when the user fills a form, and we want to make sure he/she won’t quit it by mistake.

(Full code example: https://github.com/ranwahle/image-gallery-webcomponents/tree/routing-can-deactivate)

Actually, both guard functions are the same

While he first function returns a boolean, or a Promise of boolean, the second one will do the same.
Let’s have a look at some guard example.

You can see, from the function above, that it returns a Promise, and therefore it may use both types of guards, however, from its implementation we can tell that it opens a confirmation modal, and returns it result.

When will we use this function?

This function (or guard, if you wish to stick to the Angular terminology), in our implementation will be used by assigning it to the deactivateGuard member of our route configuration

OK, but how do we use it?

On our previous post we’ve introduced the canGoOn function of our router, we will modify it a little bit so it will call our newly created function

In most cases, this function won’t use the previous URL, but nevertheless, we will send it as a parameter.

What will happen when the user presses a link in our app?

Well, that is the easier case, because we have a control over adding new route into the browser’s history. This is how our navigate function will look like

Please note, on line 23, when pushing the sate, we push our previous URL together, that’s because we need to find the previous URL, on the second case, when the user presses a back / forward button, and we have to respond to the popstate event.

OK, but what about when the user presses a “back” or “forward” ?

As you already know, in that case, the new URL is already pushed to our browser’s history, Therefore, we need to navigate back in case. We need to find the deactivate guard for the previous route and operates it. If the guard returns false or Promise of false we will navigate back.

Let’s Wrap

After supporting the mechanism of making sure we may go to a certain route, we might want to support the mechanism of navigating away from a route. We have managed to do that with a very few adjustments on our code. It took me more to write about it and explain it, than to actually implement it, nevertheless, both was fun.

Full code may be found here

--

--