DEV Community

Cover image for How to access the previous route in your Angular app
shivlal kumavat
shivlal kumavat

Posted on

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!!!

Top comments (6)

Collapse
 
nosoup4you2 profile image
NoSoup4you2

if you read the code it returns the this.previousUrl = this.currentUrl. I think its great if people spent time and contribute to community, but they should make sure what they post its valid.

Here is the revised code which works at least for me

import { Injectable } from '@angular/core';
import { Router, NavigationEnd, RoutesRecognized } from '@angular/router';
import {filter, pairwise } from 'rxjs/operators';

@Injectable()
export class PreviousRouteService {

 private previousUrl: string;

 constructor(private router: Router) {

this.router.events
  .pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
  .subscribe((events: RoutesRecognized[]) => {
    this.previousUrl = events[0].urlAfterRedirects;
    console.log('previous url', this.previousUrl);
  });
 }
 public getPreviousUrl() {
  return this.previousUrl;
 }
 } 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adriansilvadonascimento profile image
Adrian Silva

Thank you bro!
Your solution works very well.

Collapse
 
kif profile image
Kirill • Edited

Big thanks, bro. Digging a lot and only your solution works.

Collapse
 
agulab profile image
agulab

As @nosoup4you2 said, this.previousUrl == this.currentUrl. This is because it's being assigned by reference and so if you change the value of currentUrl, the referenced value of previousUrl will change too.
But we don't need to change the solution drastically, it is solved just by changing the assignation line like this:

this.previousUrl = this.currentUrl.toString();
Enter fullscreen mode Exit fullscreen mode

That way, previousUrl no longer references currentUrl, but a new string instead.
Thanks @slk5611 for your solution.

Collapse
 
brian611 profile image
Brian Pooe

This does not work.

Collapse
 
massoudyan1 profile image
Daniel Massoudyan

Doesn't work for me. It returns the current url for some reason.