Andreas
Andreas

Reputation: 1160

Is there any way to safely change LocationStrategy in Angular?

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 }) 

Upvotes: 0

Views: 1009

Answers (2)

Andreas
Andreas

Reputation: 1160

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>
......

Upvotes: 0

skouch2022
skouch2022

Reputation: 1161

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.

Upvotes: 1

Related Questions