将所有带哈希的 URL 重定向到 Angular 没有哈希的路由

Redirect all URLs with hash to Angular Routes without hash

我正在将现有的 AngularJS 1.6.x SPA 替换为 Angular 5.x SPA,并且我想让更改对我的用户透明。

我担心用户拥有现有应用程序的书签,因为它在 URL 中有散列(例如:example.com/#/menuexample.com/#/item/37);

但是,新应用在 URL 中没有散列(例如:example.com/menuexample.com/item/37)。

除了当前应用中的#/

,路径和路由都是一样的

有没有一种方法可以配置 Angular 路由以删除 #/ 并使用新应用的无哈希路由配置?

我可以复制我的所有路由以适应有和没有散列的路径,但必须有一种方法不需要加倍我的代码。

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

同样,重定向每个 #/ 路径也会使代码加倍。

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

我希望有这样的东西:

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

在此先感谢您的帮助。

我不知道这样做是否正确。但是你可以这样做:目标是订阅 NavigationChange,然后你检查你当前的路线是否以 '#!' 开头,如果是,你重定向到正确的路线。

class AppComponent implement OnInit {
    constructor(router: Router) {
        //When url change, we check if actual url have #! on it, then we redirect to the route without it.
        router.events.subscribe((event: NavigationEvent): void => {
            this.url = router.url;
            if (this.url.match('/^#!/')) {          
              this.router.navigate(
                this.url.replace('#!','')
              );
            }
          }
        );

    }
}

我认为另一种更复杂的方法是使用自定义 "matcher"。更多信息:

https://github.com/angular/angular/issues/12442

@Yanis 几乎 发布的答案有效,但需要进行一些细微的调整。他的回答绝对值得赞成;然而,下面是我实施的工作解决方案:

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