Go back button in Angular. Save route history.

Yurii K
Quick Code
Published in
2 min readAug 6, 2021

Probably every website has a back button. How should this button work? Basically, when we get a new URL address we get a new page, this URL saves in browser history. Using this history we can go back and forth. What about spa applications like angular? Most of the time in angular we have a static route but we change the inner component on the current page.

It will be good to have a back button on our website. What can we do? Standard browser history will not work for us. We can write our own service that will listen when a user changes route in our angular application. The new route will be saved, when the user clicks on the back button we give the last saved item.

Our angular application has three routes. Each component just shows the current location.

In our navigation service where we store route history, we subscribe to events of the route change. Every new route we save in an array. Obviously, this service contains a method to get the previous route and go back.

In the navigation bar we have buttons to change a route, go back button. Also, we show navigation history.

In the app component, we initialize a navigation service where we subscribe to a route change.

As a result, we have a navigation service that saves route history in our angular application.

If you need to take a close look at the project here is the link.

Originally published at http://tomorrowmeannever.wordpress.com on August 6, 2021.

--

--

Yurii K
Quick Code

Full-stack developer. In my work, I use Angular and C#. In my free time I write articles for my blog.