angulartypescriptback-buttonangular-route-segment

Back button event does not fire Angular


I am trying to redirect the user to a particular url on the click of back button in browser, and here is the code

constructor(private router: Router,private location: PlatformLocation) {        
        let eventUrl = window.sessionStorage.getItem('Event');
        this.location.onPopState(() => {
            alert('click');
            this.router.navigate(['/', this.selectedLanguage, 'event', eventUrl]);
        });
    }

but it does not seem to fire the event when user click on back button. The code is in the current component. what is the issue?

EDIT

I tried with the below answer suggested, but that too does not seems to work, the function getting called , but it still redirects to the previous page rather than the mentioned url below

unload(event: any) {
        let eventUrl = window.sessionStorage.getItem('buyerEvent');
        this.router.navigateByUrl('/' + this.selectedLanguage + '/event/' + eventUrl);
    }

Solution

  • You can bind things you want to do while leaving the app to window.unload event. Here I used the HostListener.

    @HostListener('window: unload', ['$event'])
    unload(event) {
      window.open('https://localhost:4200', '_blank');
      window.close();
    }
    

    Mention that Chrome will block window.open by default, you have to change block policy.