从 Angular 6 路由器获取语言前缀作为参数

Getting language prefix as parameter from Angular 6 router

我有一个 Angular (6.0.3) 应用程序,我想将该语言用作所有路由的通用前缀,例如 /en/foo/bar。我的路由定义 src/app/submodule/submodule.routes.ts 如下所示:

export const submoduleRoutes = [
    { path: ':lingua/foo/bar', component: FooBarComponent },
];

我的根组件src/app/app.component.ts:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, Event, NavigationEnd } from '@angular/router';

import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnDestroy {
  title = 'app';
  private sub: any;


  constructor(private router: Router, private route: ActivatedRoute) {

    this.router.events.pipe(
      filter((event:Event) => event instanceof NavigationEnd)
    ).subscribe(x => console.log(x));
  };

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       console.log(params);
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

当我导航到 /xy/foo/bar 时,会呈现 FooBarComponent。但是我无法在根组件中检索语言前缀。 params 哈希为空。

控制台输出首先为空参数显示 {},然后是 NavigationEnd 事件。

相同的代码在 FooBarComponent 中按预期工作。很明显,根组件是获取参数的错误地方

我的目标实际上是获取所有组件的 lingua 参数,以便我可以设置正确的语言。我知道我也可以将语言存储在 cookie 或本地存储中,但我需要多语言内容的可添加书签的 URL。

万一重要,源代码位于 https://github.com/gflohr/Lingua-Poly (commit 12608dc). The route in question is defined in https://github.com/gflohr/Lingua-Poly/blob/master/src/app/main/main.routes.ts(最后,:lingua/mytest

您需要让它们成为 App.component 的 children 才能正常工作。

例如:

const routes = [
  { path: ":lingua", component: AppComponent, loadChildren: 'app/main/main.module#MainModule' },
  { path: "", pathMatch: "full", redirectTo: "/en" }
]

这将从主模块加载所有 child 路由,但允许 AppComponent 访问 lingua 参数。

然后您需要从 child 路线中删除 :lingua 部分

Here is a StackBlitz example