0

I have an app that uses HashLocationStrategy and I want to change it to PathLocationStrategy. The issue is that I don't want to break existing links (ie bookmarked by users). The main idea is to receive urls like localhost:3002/#/crisis-center and redirecting to localhost:3002/crisis-center

How can I configure this apart from removing useHash from the code below?

  RouterModule.forRoot(routes, { useHash: true }) 
Andreas
  • 970
  • 18
  • 28

2 Answers2

1

I think this link has the quick answer you are looking for.

Here is the code for it:

app.component.ts


export class AppComponent implements OnInit, OnDestroy {

    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('/#', '')]);
          }
        }
      });
    }


    ngOnDestroy() {
      console.log("App Component is destroy!!");
    }
}

But I think if you have access to the web server, you should do a redirect there instead. That's because with this front-end solution, it will only work if and only if the app.component stay alive the entire time. It is possible that it might get destroyed. I added the console.log in the ngOnDestroy life cycle hook. You should test your application to see if this will ever get called.

skouch2022
  • 956
  • 1
  • 3
  • 13
  • 1
    Although the component answer is workable, and thanks for it, a server side solution is not applicable since hashes will not be sent to the server. They are mainly used by the client to navigate to parts of the page(elements having some id) in normal pages. Despite the upvote I am looking for a solution that would do the redirect from some sort of router configuration rather than the component. That would be the most suitable (accepted) answer – Andreas Jul 03 '22 at 07:38
0

I decided to contribute what I ended up doing:

Fist I thought I would give the solution in a Guard associated with my application:

@Injectable({
  providedIn: 'root',
})
export class RoutingSchemeGuardService implements CanActivate {
  constructor(
  ) {}

  canActivate(_: ActivatedRouteSnapshot) {
    if (window.location.href.includes('/#/')){
      window.location.replace(window.location.href.replace('/#/','/'))
      return false;
    }
    return true;

  }
}

As I realised, only external links would be broken. Internal ones are formed by Angular's router. Then I thought why whould I wait for the router to get triggerred so an alternative is to add it in index.html first thing first in head tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script>
      if (window.location.href.includes('/#/')){
        window.location.replace(window.location.href.replace('/#/','/'))
      }
    </script>
......
Andreas
  • 970
  • 18
  • 28