Home > Mobile >  Change the URL but don't allow the browser to load that page
Change the URL but don't allow the browser to load that page

Time:06-20

I have a link and when clicking on it, I want the URL to be /my-subpage and the browser should not load that page.

Well, this works so far. See:

<a href="/my-subpage" (click)="createCustomUrl($event, {'foo': 'bar'}, 'Page title', '/my-subpage')">
createCustomUrl(e: Event, object: any, title: string, url: string): void {
  e.preventDefault();
  window.history.pushState(object, title, url);
}

Now when the URL is /my-subpage, I want to do something. How can I do this?

This is what I have tried:

@HostListener('window:popstate')
onPopState() {
  console.log('Do something');
}

but nothing happens.

So what I am actually trying to do, is to listen to the event popstate. Well, in vanilla JS I could simply write:

window.addEventListener('popstate', event => console.log('Do something'));

I don't know how to do this in Angular, so that's why I tried it with @HostListener.

CodePudding user response:

Your code is probably not working, because you change the URL and expect from HostListener to return something at the same time. Well, popstate only detects the browser's forward and back buttons. So if you want to take an action, just put your code within your createCustomUrl() function.

However, you probably want to know the value of foo. In this case, your HostListener needs an event. So the following code should work, if you click on your custom link and then press the browser's back button and then the forward button:

@HostListener('window:popstate', ['$event'])
onPopState(event: PopStateEvent) {
  if (event.state) {
    console.log(event.state.foo); // This returns 'bar'
  }
}

CodePudding user response:

Please try this:

constructor(
  private router: Router
) {
  router.events.pipe(
    filter(event => event instanceof NavigationStart)  
  ).subscribe((event: NavigationStart) => {
     // You only receive NavigationStart events
    console.log(event.url);
  });
}

For a strict mode you can try this:

constructor(
  private router: Router
) {
  router.events.pipe(
    filter((event): event is NavigationEnd => event instanceof NavigationStart)  
  ).subscribe((event: NavigationStart) => {
     // You only receive NavigationStart events
    console.log(event.url);
  });
}
  • Related