-1

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.

  • I guess a url with hash would match an empty route, basically home? If so, you could have a listener there that checks for a hash in the url and reroute the customer to the correct path? That’s what I would try. – MikeOne Mar 15 '23 at 19:55

1 Answers1

0

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.

Flo
  • 2,232
  • 2
  • 11
  • 18
  • Thank you Flo! By the way, is it possible to do this redirection via Apache configuration? Would it be a better solution? – Luis Fernando Mar 16 '23 at 17:23
  • I‘m not a Apache expert. But I think yes, you can do it, too if you wanna only replace it. – Flo Mar 17 '23 at 06:03