Search code examples
angularurlhash-location-strategy

Hash (#) in URL - Angular


I have an Angular 14 application that uses HashLocationStrategy - # in URL (Example: https://localhost:4200/#/agenda?data=2023-03-22).

Some of my customers have tried to post stories on Instagram, but Instagram "cuts" the URL from the hash (#), leaving it as https://localhost:4200/.

I would like to switch to PathLocationStrategy, without the hash (Example: https://localhost:4200/agenda?data=2023-03-22).

However, I already have many customers who use the URL WITH HASH.

Is it possible to make my application accept URLs with and without hash?

Or another solution?

Thank you.

My application accept URLs with and without hash.


Solution

  • A LocationStrategy used to configure the Location service to represent its state in the hash fragment of the browser's URL.

    So this means: You can't. Its a injected Service and you cannot change it on runtime. But what you can do is the follow:

    My opinion is: Do not mix it. But if you must do it, here is a solution:

    In your App Component

    export class AppComponent implements OnInit {
        constructor (private router: Router) { }
    
        ngOnInit() {
          this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
              if (!!event.url && event.url.match(/^\/#/)) {
                this.router.navigate([event.url.replace('/#', '')]);
              }
            }
          });
        }
    }
    

    The original Answer is here. With this code you can replace the #, or not. What you want.

    Note... I know..

    I know that looks a little hacky at first. But there is no way (and if so there is no good way) to change the LocationStrategy in Angular dynamically in runtime.