Many times we may want to access the previous page/route URL in Angular application for any requirement such as implementing custom back button inside the application.

We will be able to access the current page URL using the ‘Router’ or  params/query params values using ‘Activated Route’. Angular do not provide previous URL information by default.

How to get the Previous Route URL in Angular ?

Whenever a Router event happens, Angular gives access to that event through the ‘events’ observable which will be available on Router. We can subscribe to this observable and save the ‘URL’ information whenever a user reaches the end of the Navigation (whenever a new route loads).

We created an application to demonstrate this with Home, Product, Productid, Notfound components and a Service to save the URLs information.



Copy to Clipboard



Copy to Clipboard



Copy to Clipboard

AppComponent HTML:


Copy to Clipboard

We did not make any changes to any other files.

Explanation about the logic:

When we subscribe to the ‘events’ observable of Router, we get information about each and every Router event. We have added a ‘pipe’ to the events observable to filter only the events that of type ‘NavigationEnd’ (which means the navigation from previous route to new route ended and the new route loaded) by using the ‘filter’ operator from ‘rxjs’ which acts similar to the ‘filter’ method of JavaScript which is available to arrays.

We received the information only about the ‘NavigationEnd’ events inside the subscription and assigned the ‘url’ from it to the ‘currentUrl’ property of AppService.