I am creating project using angular. In my project i need to handle the browser back button. The requirement is when user click on back button it should be logged out
Login Url is different and dashboard is different.
Below is the implementation
// app.component.ts
@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
history.pushState('back', null, null);
// log out url
}
But above code is not working when user just landed on the dashboard
CodePudding user response:
I'm not a fan of using window:popstate
because it feels like it shouldn't be used in Angular. A better method of listening for popstate events is to subscribe to the location service:
import {Location} from "@angular/common";
constructor(private location: Location) { }
ngOnInit() {
this.location.subscribe(event => {
//do something
});
}
a big plus: you can unsubscribe any time you want.
Please keep in mind that as with window:popstate
it won't directly detect if you went back or forth. It only fires when it has detected that the route params have changed which ALSO happens when the user hits the forth button.
CodePudding user response:
You can use the fromEvent
of RxJS to listen to popstate
events.
In your root component.ts file,
- Import the
fromEvent
fromRxJS
as shown below.
import { fromEvent } from 'rxjs';
- Define a subscription listening to
popstate
event and subscribe to it inside theOnInit
lifecycle hook and unsubscribe inngOnDestroy
lifecycle hook to stop listening to changes, as shown in the following snippet.
navigationChangeEvent = fromEvent(window, 'popstate');
ngOnInit() {
this.navigationChangeEvent.subscribe((event) => {
console.log(event.currentTarget.location.pathname);
});
}
ngOnDestroy() {
this.navigationChangeEvent.unsubscribe();
}