loading...
Stack Labs

Angular Router • Popstate blocked

ruizalexandre profile image Alexandre Updated on ・1 min read

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 !! 🔥🚀

Posted on by:

Stack Labs

Premier Google Cloud Partner, STACK LABS is a company of tech ❤️ enthusiasts at the service of its customers with Cloud, Big Data, Backend, Frontend & Security projects ... Our Partners: Google, AWS, Gitlab

Discussion

markdown guide