How to go back to the previous URL in Angular?

Image for post
Image for post

As a developer, there is no limit to learning. We always need to be up to date with technologies as well as the upcoming or current features which are trending in the market.

Recently, I was looking for the best way to optimize my angular code.I have gone through a lot of articles and as we know it is limitless. Then I thought of consolidating the checklist for writing cleaner code for Angular which helped me and might help others too.

These small articles not only help you to write a better TypeScript or JavaScript Code but also clear the concepts of front-end technologies. This will help you to build your strong base and can help you in the upcoming frontend interviews.

One of the most basic topics in any programming is navigating from one component to another component. Sometimes we do get requirements to go to previous routes and it might be difficult if we don’t know the efficient solution for this. Let’s discuss two ways to navigate to a previous page in Angular.

1.We can take advantage of the built-in Location service, which owns a “Back” API.

Here (in TypeScript):

2. We can create a service to handle all router related events.

export class RouterService {
private _prevURL: string;
private _currURL: string;
private _routeHistory: string[];
constructor(router: Router) {
this._routeHistory = [];
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
private _setURLValues(event: NavigationEnd): void {
const tempUrl = this._currURL;
this._prevURL = tempUrl;
this._currURL = event.urlAfterRedirects;
get previousUrl(): string {
return this._prevURL;
get currentUrl(): string {
return this._currURL;
get routeHistory(): string[] {
return this._routeHistory;

Are you preparing for interviews? Here are frequently asked interview questions in Angular. It covers the Latest interview questions for Angular and Frontend development. Let’s check how many of these questions you can answer?

Written by

Writing about Angular,JavaScript and Type Script related articles. Please follow, clap stories to motivate us writing more!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store