Search code examples
angularangular-router

Redirect all URLs with hash to Angular Routes without hash


I'm replacing an existing AngularJS 1.6.x SPA with an Angular 5.x SPA and I want to make the change transparent to my users.

I'm concerned about users who have bookmarks to the existing app because it has hashes in the URLs (for example: example.com/#/menu and example.com/#/item/37);

However, the new app does not have hashes in the URLs (for example: example.com/menu and example.com/item/37).

The paths and routing are all the same, with the exception of the #/ in the current app.

Is there a way I can configure the Angular routing to drop the #/ and use the hash-free routing configuration of the new app?

I could duplicate all of my routing to accommodate paths with and without the hash, but there must be a way that doesn't require doubling my code.

// Don't really want to do this:
const routes: Routes = [
  {
    path: 'menu',
    component: MenuComponent
  },
  {
    path: '#/menu',
    component: MenuComponent
  },
  // etc.
];

Similarly, redirecting every #/ path would double the code, too.

// Don't really want to do this:
const routes: Routes = [
  {
    path: 'menu',
    component: MenuComponent
  },
  {
    path: '#/menu',
    redirectTo: 'menu'
  },
  // etc.
];

I'm hoping there is something along these lines:

{
  path: '#/*',
  redirectTo: '*' // Somehow reference the wildcard part of the path here 
}

Thanks in advance for your assistance.


Solution

  • The answer posted by @Yanis almost worked, but required a few slight tweaks. His answer definitely deserves an upvote; however, below is the working solution I implemented:

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