0

Suppose I have two routes :

{ path: '/path1', component: component1 }
{ path: '/path2', component: component2 }

and I am at '/path1' and navigating to '/path2'.

So my question is how get route url '/path1' in component 2 constructor or anywhere in code without using resolve or global variable through any service.

Component2.ts

export class Component2{
    constructor(router: Router) {
        router.events.subscribe((event) => {
            // here I want to get route url '/path1' from component1
        });
    }
}

Please let me know if anyone needs more clarification.

Community
  • 1
  • 1
Mohsin Hasan
  • 156
  • 9
  • 2
    Possible duplicate of [How to determine previous page URL in angular2?](https://stackoverflow.com/questions/41038970/how-to-determine-previous-page-url-in-angular2) – Tudor Ciotlos Dec 27 '17 at 11:58
  • No, it will not gonna solve my problem since here they are saving route url before navigation into some variable previousUrl: string, but What I want is to get url of that page from where navigation gets start i.e., Component1 in other component where navigation end i.e. in Component 2. – Mohsin Hasan Dec 27 '17 at 12:04

2 Answers2

1

I'm not sure how you would like to use it. But if you know the available paths in the app you could simply use in component2 something like: this.router.navigate(["/path1"]); Base URL you can get using for example: location.host So your url would be location.host + "/path2" Is that what you are looking for?

KrystianC
  • 422
  • 3
  • 13
  • Why should I navigate to same route from where I am coming. whats my problem is that I have to implement some business logic based on the last route visited. – Mohsin Hasan Dec 28 '17 at 04:14
0

store the current event so you can use it when the next happens

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