我有一个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(提交12608dc)。有问题的路线在https://github.com/gflohr/Lingua-Poly/blob/master/src/app/main/main.routes.ts中定义(最后是:lingua/mytest
。
答案 0 :(得分:0)
您需要让他们成为App.component
的子代才能起作用。
例如:
const routes = [
{ path: ":lingua", component: AppComponent, loadChildren: 'app/main/main.module#MainModule' },
{ path: "", pathMatch: "full", redirectTo: "/en" }
]
这将从主模块加载所有子路由,但允许AppComponent
访问lingua
参数。
然后,您需要从子路径中删除:lingua
部分