All Articles

Angular location service

There is a small and well hidden service inside Angular: the location service. As the name and documentation suggests, this is a class that is used to interact with the browser URL.

I’ve seen people using this, probably by mistake, trying to navigate inside an application, this is not working because it’s not related to the router at all. We can use it to update/change the browser address, basically interacting with the URL outside of routing.

Use case

A nice place that I’ve found for this to use is to update the current location after we finish an operation that would normally change it, but we don’t want to involve the router (for example, to avoid any side effects and navigation triggers generated by a reload of the page).

Lets say we have a route that goes to an item details, something like: ‘item/{itemId}’ and a very similar one that is used to create a new item: ‘item/new’.

When we create a new item we navigate to the last one and the browser address is set to item/new. After we add all the details when we send this to the API we get back the saved entity from the database, including the item id.

Since the item was saved, we’re no longer in the new state, we’re in edit mode and we want to show this in the URL by changing new with ***id **value*.

We could reload the page, but this will most probably fetch again the item from the API. And this in the most simple scenario, in more complex ones we can have multiple effects that are triggered when the page is loaded and we want to avoid all that extra stuff.

Solution

Here comes to the rescue the location service. We can use the **go** method to update the address and to add it to the history, making sure that if we go to a different route and hit back button, we’ll end up with the item id in the address bar and not with new.

Using the method is as simple as calling it with a string argument representing the new address:

Code

A sample, and very small, application that shows this can be found on StackBlitz. If you want to edit the sample you can use this link.

What other use cases did you find for the Location service ?