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.
We did not make any changes to any other files.
Explanation about the logic:
We received the information only about the ‘NavigationEnd’ events inside the subscription and assigned the ‘url’ from it to the ‘currentUrl’ property of AppService.
Leave A Comment