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);
}