7

How can I get the previous route as a path in Angular?

I tried using a solution via this link, but it does not execute on first page load.

constructor(router: Router) {
  router.events
  .pipe(filter(event => event instanceof NavigationEnd))
  .subscribe((event: NavigationEnd) => {
    console.log('prev:', event.previousUrl);
    this.previousUrl = event.url;
  });
}

I used both RoutesRecognized and NavigationEnd, however they did not work.

I called this method in the constructor and ngOnInit, but neither of them execute on first page load.

Is there any method of obtaining the previous URL?

Thank you.

Graham John
  • 170
  • 12
Ricky
  • 693
  • 3
  • 12
  • 20

3 Answers3

18

In a constructor you can use

this.router.getCurrentNavigation().previousNavigation.finalUrl.toString()

to get the previous route path

Be careful if you use this.router.getCurrentNavigation() outside a constructor it will be too late from life cycle and you will always have a null value

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().previousNavigation.finalUrl.toString());
}
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
2

The Router class exposes a getCurrentNavigation() method:

getCurrentNavigation(): Navigation|null {
  return this.currentNavigation;
}

Router.currentNavigation is of type Navigation:

private currentNavigation: Navigation|null = null;

As we can see from Navigation's definition, you can access the previous navigation with the previousNavigation property:

previousNavigation: Navigation | null;

So, you could use this property to get the previous path.


Update

As O.MeeKoh suggested, getCurrentNavigation() must be called from the constructor.

Andrei Gătej
  • 11,116
  • 1
  • 14
  • 31
0

you can try navigationStart to resolve your problem of not getting the previous route for the first time.

you can refer the below lines of code for the getting the idea how to us that.

ngOnInit(){
    this._router.events.filter(e => e instanceof NavigationStart )
      .bufferCount(2,1).subscribe(e => {
        if(e !== null && e !== undefined) this.orginalPath = e[0]['url'].substr(1)
    });
  }

Even you can try the method pairwise() if it resolves your problem.

router.events
  .pipe(
    filter(e => e instanceof NavigationEnd),
    pairwise() // check it's second route load
  )
  .subscribe((e: any[]) => {
    console.log(e);
  });
Minal Shah
  • 1,402
  • 1
  • 5
  • 13