Angular Router • Popstate blocked
Alexandre
Posted on December 9, 2019
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.
ENJOY !! 🔥🚀
💖 💪 🙅 🚩
Alexandre
Posted on December 9, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
angular Safely Experiment with Angular 18: A Guide for Developers with Existing 16 & 17 Projects
July 16, 2024