How to access the previous route in your Angular app

slk5611

shivlal kumavat

Posted on January 25, 2021

How to access the previous route in your Angular app

The blog is all about access the previous route in your Angular app. In a simple way this service work like:

  • it saves the current url, after that, when a NavigationEnd event fires.

  • it saves that url in a variable previousUrl, to be get in your component.

First create a new service PreviousRouteService. If you're using the Angular CLI, use the command ng generate service previous-route and add in your app.module file.

Your service file will look like below:

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

@Injectable()
export class PreviousRouteService {

  private previousUrl: string;
  private currentUrl: string;

  constructor(private router: Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {        
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl() {
    return this.previousUrl;
  }    
}
Enter fullscreen mode Exit fullscreen mode

You can use in your component like below:

To use the previous route url in your component, first importing the service:

import { PreviousRouteService } from '../services/previous-route.service';
Enter fullscreen mode Exit fullscreen mode

Inject it into the constructor like below:

constructor(
  private previousRouteService: PreviousRouteService
) {}
Enter fullscreen mode Exit fullscreen mode

Now you can access the previous url with this.previousRouteService.getPreviousUrl().

ngOnInit() {
  console.log(this.previousRouteService.getPreviousUrl());
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading if any suggestion please comment below!!!

Happy Coding!!!

💖 💪 🙅 🚩
slk5611
shivlal kumavat

Posted on January 25, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related