3

I want to get the previous and current URL to set variables prevUrl and currentUrl in Angular 8.
I have two components. StudentComponent and HelloComponent .
When I navigate from HelloComponent to StudentComponent

In StudentComponent constructor prevUrl and currentUrl have value
But when I clicked showUrl button then in console of browser show
prevUrl undefined
currentUrl undefined

How can I solve this problem? Why prevUrl and currentUrl in the constructor have value but in button doesn't value?

student component:

prevUrl:string;
currentUrl:string;
 constructor(private router: Router, private route: ActivatedRoute) {

    this.router.events
            .pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
            .subscribe((events: RoutesRecognized[]) => {
                this.prevUrl = events[0].urlAfterRedirects;
                this.currentUrl = events[1].urlAfterRedirects;
                console.log('this.prevUrl constructor', this.prevUrl);
                console.log('this.currentUrl constructor', this.currentUrl);
            });

 }

button:

showUrl = ()=>{

    console.log('prevUrl',this.prevUrl);
    console.log('currentUrl',this.currentUrl);
  }

stackblitz

Mohammad Daliri
  • 1,370
  • 6
  • 20
  • 43
  • 1
    The code looks like its working, but you'll need to have that code in a service and not the component. check this: https://stackoverflow.com/questions/41038970/how-to-determine-previous-page-url-in-angular. – C.OG Dec 24 '19 at 12:55
  • Forked your stackblitz to show whats going on. Notice how the `subscribe event` never fires: https://stackblitz.com/edit/so-get-the-previous-and-current-url-in-angular-8 – C.OG Dec 24 '19 at 12:59
  • 1
    `StudentComponent` is destroyed and recreated when the route changes. You need to move your logic to the `AppComponent` or a shared service so that code can listen for route changes. – Reactgular Dec 24 '19 at 13:04
  • @C_Ogoo Thanks. this [answer](https://stackoverflow.com/a/48866813/2585074) can help me – Mohammad Daliri Dec 24 '19 at 13:28
  • @Reactgular Thanks I add a service and used in StudentComponent and worked true.[stackblitz](https://stackblitz.com/edit/angular-route-event-and-service) – Mohammad Daliri Dec 24 '19 at 13:32

1 Answers1

2

Try like This :

this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {        
        this.prevUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
 });

Live Demo: https://stackblitz.com/edit/angular-route-event-hr2xsc

Rahul Dapke
  • 345
  • 6
  • 19