【问题标题】:Redirect all URLs with hash to Angular Routes without hash将所有带散列的 URL 重定向到不带散列的 Angular 路由
【发布时间】:2018-03-27 18:10:39
【问题描述】:

我正在用 Angular 5.x SPA 替换现有的 AngularJS 1.6.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 
}

提前感谢您的帮助。

【问题讨论】:

标签: angular angular-router


【解决方案1】:

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

【讨论】:

  • 这对我有用,但你为什么要使用双重否定! ?
  • @awebdev - 我使用双键 (!!) 将真/假值转换为严格的布尔类型。在我的代码中,event.url 是一个字符串,而 !!event.url 是一个由 if 语句计算的布尔值。如果 event.url 有值,则 !!event.url 为真,否则,如果没有值,则为假。见bennadel.com/blog/…
  • 啊,有道理,我从来没有花时间去了解人们为什么使用!!。谢谢!
  • 另一件事 - 你是如何处理 301 的?你在你的服务器上配置了吗?
  • 请注意,如果 URL 包含查询字符串,例如 /some/path?foo=1&bar=2,这将不起作用,因为路由器编码 ?&navigateByUrl 在这种情况下效果更好:this.router.navigateByUrl(event.url.replace('/#', ''));
【解决方案2】:

我不知道这样做是否正确。但是您可以这样做:目标是订阅 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('#!','')
              );
            }
          }
        );

    }
}

我认为另一种更复杂的方法是使用自定义“匹配器”。更多信息在这里:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多