How to Get the Previous URL in Angular?

In Angular, there is no predefined method that can help you get the previous URL directly. But, we know one thing, there are plenty of methods available which return the current route/URL of your Angular application.

So, if anyhow, we store the current URL somewhere, let’s say in a service file or in the local storage of your browser, and navigate to some other route then this URL will become the previous URL for us.

So, long story short, we will create two variables, the currentURL and previousURL in our component’s ts file. And every time we navigate to a new route, we will first copy the value of the currentURL into the previousURL variable and then update the currentURL with the route we are currently on.

To get the current URL, we will subscribe to the Router events. And filter only those events which are the instances of the NavigationEnd. In case you don’t know, a NavigationEnd event fires when the navigation ends successfully.

So, open up your component’s ts file(any component you want) and paste the below code into it:

import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  previousURL: string = '';
  currentURL: string = '';

  constructor(private router: Router) {

  }

  ngOnInit(): void {
    this.router.events.subscribe(
      (event: any) => {
        if (event instanceof NavigationEnd) {

          this.previousURL = this.currentURL;
          this.currentURL = event.url;

          console.log(this.previousURL);
          // Prints the previous URL you visited
          // Eg:- /login          
        }
      }
    );
  }

  // Add other stuff
}

As we have subscribed to the Router events, so it always keeps on running and prints the previous URL every time we navigate to a new route. But the thing is, you have to visit this component’s route at least once. Else you have to add this code to your app.component.ts file.

If you want to get rid of it, you can unsubscribe from the router events when the component destroys i.e. inside the ngOnDestroy() life cycle hook. In that case, the previous URL will only get printed if you visit the component where you added the above code.

But, if you want to make the previous URL globally accessible, you can either store it in the local storage or in a common service. We will go with the second approach.


Making Previous URL Globally Accessible using Service

The previousURL variable we were working with so far is only accessible inside a single component. But, we want to make it globally accessible so that it can be used anywhere to keep track of the previous URL we have visited.

To do that, let’s first create a service common.service.ts using the ng g s command. This service file will have a behavior subject which will hold the value of the previous URL and an observable which can be subscribed from any component to get the value of the previous URL.

The behavior subject and observable can be imported from the rxjs library.

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  previousUrl: BehaviorSubject<string> = new BehaviorSubject<string>('');
  previousUrlObs: Observable<string> = this.previousUrl.asObservable();

  constructor() { }
}

The previousUrl behavior subject contains an empty string as its default value but it doesn’t do anything for now.

So, if we want it to hold the updated previous URL value, we have to call the next() method on it. As soon as the next() method invokes, the behavior subject will hold the updated value, and any component that subscribes to the previousUrlObs observable will get the updated value of the previous URL.

So, let’s add a method in our service file that will update the previous URL value:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  previousUrl: BehaviorSubject<string> = new BehaviorSubject<string>('');
  previousUrlObs: Observable<string> = this.previousUrl.asObservable();

  constructor() { }

  // Set updated value
  setPreviousUrl(previousURL: string) {
    this.previousUrl.next(previousURL);
  }

}

You will have to call the setPreviousUrl() method wherever you are subscribing to the Router events. In our case, we subscribed to the Router events inside the products.component.ts file’s ngOnInit() method. So, we have to call it there.

This is how the modified code will look like:

import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { CommonService } from '../common.service';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  previousURL: string = '';
  currentURL: string = '';

  constructor(private router: Router, private commonService: CommonService) {

  }

  ngOnInit(): void {
    this.router.events.subscribe(
      (event: any) => {
        if (event instanceof NavigationEnd) {

          this.previousURL = this.currentURL;
          this.currentURL = event.url;
          
          this.commonService.setPreviousUrl(this.previousURL);
          // Update the previous URL 

        }
      }
    );
  }

  // Add other stuff  
}

Get the Updated Previous URL in Any Component

If you want to get the updated value of the previous URL in any component, you can simply subscribe to the previousUrlObs observable and get the updated value as a response.

This is how you can do it in your ts file:

import { Component, OnInit } from '@angular/core';
import { CommonService } from '../common.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private commonService: CommonService) { 
    
  }

  ngOnInit(): void {
    this.commonService.previousUrlObs.subscribe(
      (previousUrl:string)=>{

        console.log(previousUrl)
        // Prints the previous URL
      }
    )
  }

}

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.