3

I need your assistance to get the previous route path. I am using the below link to get that but it doesn't trigger at first time...

How to determine previous page URL in Angular?

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 but didn't get that..

I called this method in constructor and ngOnInit but every time it doesn't trigger at first time....

is there any way, I can get that...

Thanks...

Ricky
  • 629
  • 2
  • 12
  • 19

3 Answers3

2

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
  • 4,594
  • 3
  • 17
  • 26
1

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.

Andrei Gătej
  • 9,988
  • 1
  • 12
  • 28
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,281
  • 1
  • 4
  • 12