代码之家  ›  专栏  ›  技术社区  ›  Guido Flohr

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

  •  1
  • Guido Flohr  · 技术社区  · 7 年前

    我有一个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 , the FooBarComponent 得到渲染。但我无法在根组件中检索语言前缀。这个 params 哈希为空。

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

    相同的代码在 FOB组件 . 显然,根组件是获取参数的错误位置。

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

    如果这很重要,源代码位于 https://github.com/gflohr/Lingua-Poly (提交12608DC)。有关路线的定义见 https://github.com/gflohr/Lingua-Poly/blob/master/src/app/main/main.routes.ts (最后, :lingua/mytest .

    1 回复  |  直到 7 年前
        1
  •  0
  •   user184994    7 年前

    你需要让他们成为 App.component 让它发挥作用。

    例如:

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

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

    然后需要移除 :lingua 从您孩子的路线中分离出来

    Here is a StackBlitz example