首页 > 解决方案 > 在Angular 6中的url地址栏上隐藏语言默认值

问题描述

我是新手,我在 Angular 6 中遇到路由器问题。我有三种语言:en、de、fr。所以现在,我在地址栏上的网址是:

但我想使用 En(默认语言),我的 url 应该是这样的:

剩下的就是:

这是我的配置路线:

 const routes: Routes = [
     {
        path: ':lang/home',
        component: LandingPageComponent,
        children: LandingPagePageRoutes
     },
     {
        path: ':lang/product',
        component: ProductSinglePageComponent,
        children: ProductPageRoutes
     },
     {
        path: '',
        redirectTo: `/${LANG}/home`,
        pathMatch: 'full'
     },
     {
        path: '**',
        redirectTo: `/${LANG}/home`,
     }
 ];

我们可以这样做吗?如果是,请给我一些例子?非常感谢!

标签: angularrouterangular6

解决方案


因为 Angular 不允许从另一个重定向进行重定向,所以我认为您可以这样做的一种方法是,在您的根组件的构造函数中app.component.ts,您可以在应用程序启动时获取页面的 url,然后重定向到localhost:4200/homeif它是localhost:4200/en/home。您的代码将如下所示。

app.component.ts

import { Router } from '@angular/router';

constructor(private router: Router) {
  if(this.router.url === "/en/home"){
        router.navigateByUrl('/home')
    }
 }

然后在你的路由模块中,你应该有一个匹配的 url/home

像这样的东西。

 {
    path: 'home',
    component: EnglishLandingPageComponent
 }

推荐阅读