【问题标题】:Translate my Url Angular 2 - Typescript翻译我的 URL Angular 2 - 打字稿
【发布时间】:2017-12-20 00:41:07
【问题描述】:

Angular2 - TypeScript - ng-Translate

大家好,

我需要根据选择的语言“en/soybean”、“fr/soya”更改我的 URL 的其余部分。在我的 app.routes 中,我得到了这条路径:

{ path: ':lang/soybean', component: SoybeanComponent }

我的 SoyBean 组件是使用 ng-translate 从 lang 参数转换而来的

this.route.params.subscribe(params => {
   translate.use(params['lang']);
})

如何将网址显示为 fr/soya 但仍使用路径 fr/soybean !?

我尝试了什么

*我创建一个新路径:{ path: ':lang/soya', component: SoybeanComponent }, 我以为我可以将用户重定向到好的路径:

 if(params['lang'] === 'en'){
       this.router.navigateByUrl('lang/soybean');
    }
    if(params['lang'] === 'fr'){
       this.router.navigateByUrl('lang/soya');
    }

但它会导致无限加载。
然后我想我可以在重定向后对 lang 参数进行硬编码:

if(params['lang'] === 'en'){
       this.router.navigateByUrl('en/soybean');
    }
    if(params['lang'] === 'fr'){
       this.router.navigateByUrl('fr/soya');
    }

但在这种情况下,我会捕获一个异常。*

【问题讨论】:

  • 您似乎将lang 视为路由参数和常量路径路由?
  • lang 确定我将使用的女巫语言,但它并没有改变路径。如果lang 是fr,那么soy.html 和soy.component 将被翻译成法语。我想要的是如何将网址显示为 fr/soya 但仍使用路径 fr/soybean !抱歉解释不好,我会编辑我的第一篇文章!

标签: angular typescript url translate


【解决方案1】:

你把它复杂化了:-)。 只是使用了带有反引号的模板字符串

url = `${lang}/${i18name}`

【讨论】:

  • 这是角度 2 吗?你能准确地说出你在哪里以及如何使用它!因为我在 app.routes.ts 中定义了我的 url,就像 { path: ':lang/soybean', component: SoybeanComponent } ?谢谢!
  • 嗯,它已经融入了 Typescript,这是 Angular 2 和 4 的基础。 basarat.gitbooks.io/typescript/content/docs/…
【解决方案2】:

我用 location.replace(newUrl) 找到了我自己的解决方案

我创建了一条新路径:{ path: ':lang/soya', component: SoybeanComponent }

在我的组件中我使用 location.replace(url)

 this.route.params.subscribe(params => {
            translate.use(params['lang']);
            switch (params['lang']) {
                case 'en':
                    location.replace(`index.html#/${params['lang']}/soybean`)
                        break;
                case 'fr':
                    location.replace(`index.html#/${params['lang']}/soya`);
                        break;
            }

        })

这对我有用!如果您知道更好的解决方案,我将很高兴听到它!谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2017-11-07
    • 2020-04-07
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多