Angular - How to change the url in without modifying the history

550 Views Asked by At

I would like to change the url of my page, but without changing the angular history state nor reloading the page.

Is this somehow possible ?

Already tried

Method no history changes not reloading changing the url
location.replaceState(url) not working working working
router.navigateByUrl(url, {skipLocationChange: true, }) working not working working

A bit of context

I'm adding the /de at the beginning of the url -> so from /my-url to /de/my-url.

But actually, the existing route is /my-url so for navigation through my app I've added a guard that.

  1. Control the url
  2. If it does have the /de remove it and router.navigate(urlWithoutDe)
  3. Add it back again to visually see the /de (or any other language like /en, /fr, ...)
  4. But when the user navigate back with the back button, the guard wont be triggered, so it will try to navigation to /de/my-url which does not exists..
1

There are 1 best solutions below

3
AsGoodAsItGets On

Did you try listening to the beforeunload event in your app.component, something like this:

@Component({ 
    selector: 'app-root',
    ..
)}
class AppComponent {
    @HostListener('window:beforeunload')
    navigateToActualUrl() {
        // detect if the user is trying to load an invalid URL
        // not sure if location contains the "wrong" URL at this point
    }
}

https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent

As a general note, Angular Guards will not be triggered when the user clicks on the back/forward buttons, you need to listen for this event.