-1

There are different ways through which I know the current route in angular.
I would like to know the previous route. Say for example I'm in a tab
http://localhost:4200/test/testNav/ABC.
Now, I click another tab that takes me to
http://localhost:4200/test/SampleNav/XYZ.

In the ngOnInit() method of this HTML "http://localhost:4200/test/SampleNav/XYZ" I want to get the previous URL which is /ABC.

this.router.url, this.activatedRoute.snapshot all gives me the currenturl.

Is there a way to get the previous URL from the available angular components?

Basically, when I come to XYZ page from ABC I should do something and when I come to XYZ from CBA I should do something else. Any inputs highly appreciated.

greybeard
  • 2,249
  • 8
  • 30
  • 66
Geek
  • 3,187
  • 15
  • 70
  • 115
  • 1
    https://stackoverflow.com/a/47880387/7365461 https://stackoverflow.com/a/48866813/7365461 Check out those links.\ – AliF50 Oct 22 '20 at 21:41
  • @AliF50 From my point of view creating service for one previous url is little bit overkill in case of 1 or 2 time usage – Franky238 Oct 22 '20 at 21:53
  • I agree but the first link I posted doesn't have to be in a service, it can be in a component. – AliF50 Oct 22 '20 at 21:55
  • @AliF50. Thank you. how do i get the value of param from the redirect link say for example events[0].urlAfterRedirects gives me '/inventoryDetails;test=0;id=45', I want to get the value of id from this. How can i do without using subString – Geek Oct 26 '20 at 17:30
  • I wouldn't mind using `substring` for that but try logging out `events[0]` (console.log(events[0]) to see if you get a params object or anything of that sort that can give you extra information. – AliF50 Oct 26 '20 at 17:55

1 Answers1

0

Here comes getCurrentNavigation() used with optional chaining (question mark) because it can be null. There you can take previousNavigation and finalUrl will return you an UrlTree. Next just execute navigation on finalUrl if it is not null.

const urlTree = this.router.getCurrentNavigation()?.previousNavigation?.finalUrl;
if (urlTree) { 
  this.router.navigateByUrl(urlTree);
}
   
Franky238
  • 511
  • 5
  • 21