There is my solution to block the popstate event in Angular world.
import { Location } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(
private location: Location,
private router: Router
) {
this.router.events
.pipe(
filter(
(event: NavigationStart) => event.navigationTrigger === 'popstate'
)
)
.subscribe(() => {
this.router.navigateByUrl(this.router.url);
this.location.go(this.router.url);
});
}
}
How it works ?
First of all, listen router events and filter on navigationTrigger (only NavigationStart). If "popstate" value, apply the logic.
Wait, why two actions ? 🤔
this.router.navigateByUrl(this.router.url);
Angular navigates on the last route without reloading the page (no guards triggered again)
But browser perform real navigation !
If you click again on back button, browser navigation continues
How to freeze browser URL when popstate ?
this.location.go(this.router.url);
location.go
method rewrite browser URL WITHOUT reloading the page.
Top comments (0)