【问题标题】:Angular routing - how to formulate path?角度路由 - 如何制定路径?
【发布时间】:2019-11-30 06:34:40
【问题描述】:

目标:我希望将站点路由到 EN 或 ES 版本。更具体地说,如果他们选择西班牙语,则应该:

基本上我需要 localhost:4200/en 去 localhost:4200/es

如果他们选择英语,反之亦然。

但是,我无法对其进行硬编码,因为 Dev/Rel/Prod 的根不同。

问题:它总是路由到:http://localhost:4200/en/#/es

我的尝试

当我这样做时:

if (event.value == "es") { this.routerService.navigate(['/es/']); }   

我明白了:

http://localhost:4200/en/#/es

我也得到相同的结果:

if (event.value == "es") { this.routerService.navigate(['es/']); }
if (event.value == "es") { this.routerService.navigate(['/es']); }

预期结果http://localhost:4200/es/ 实际结果http://localhost:4200/en/#/es

【问题讨论】:

  • 请您包含您的路由文件并说明您使用什么进行翻译?
  • 路由器允许导航到应用程序的路由。不是其他应用程序的 URL。使用一个普通的旧链接,window.location
  • 我认为 this.routerService.navigate(['/es'] 应该与 router.navigate 一起使用。如果您使用的是window.location,请尝试window.location.href = '/es'
  • @AshotAleqsanyan ,我尝试使用 window.location.href。我做了 window.location.href = window.location.hostname + "/es/" 。根据调试器,主机名是 localhost。但它仍然指向:localhost:4200/en/localhost/es
  • 请你试试这个window.location.href = '/es'

标签: angular typescript


【解决方案1】:

您的路由器基本路径似乎包含/en。你有两个选择。

1) 像这样使用../relativeTo: this.route 向后导航:

this.routerService.navigate(['../es'], {relativeTo: this.route});

你必须像这样在构造函数中注入route

constructor(
    private routerService: Router,
    private route: ActivatedRoute, {
  }

2) 从基本路径中删除/en 并使用:

switch(event.value) {
  case 'es': 
    this.routerService.navigate(['/es']);
    break;
  case 'en':
    this.routerService.navigate(['/en']);
    break;
}

【讨论】:

  • 谢谢。我尝试了选项 1。我使用了 ../.出于某种原因,我只能返回 localhost:4200/en/#。所以当我使用它时,我仍然得到localhost:4200/en/#/es
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 2015-06-13
  • 2018-09-02
  • 1970-01-01
相关资源
最近更新 更多