javascript - Getting language prefix as parameter from Angular 6 router
问题描述
I have an Angular (6.0.3) application and I want to use the language as a common prefix to all routes, something like /en/foo/bar
. My route definition src/app/submodule/submodule.routes.ts
looks like this:
export const submoduleRoutes = [
{ path: ':lingua/foo/bar', component: FooBarComponent },
];
My root component 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();
}
}
When I navigate to /xy/foo/bar
, the FooBarComponent
gets rendered. But I am not able to retrieve language prefix in the root component. The params
hash is empty.
The console output first displays {}
for the empty params, and then the NavigationEnd
event.
The same code works as expected in the FooBarComponent
. Obviously, the root component is the wrong place to get the parameters.
My goal is actually to get the lingua
parameter for all components, so that I can set the correct language. I know that I could also store the language in a cookie or local storage but I need bookmarkable URLs for the multi-lingual content.
In case that matters, the source code is at 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 (at the end, :lingua/mytest
.
解决方案
你需要让他们成为它的孩子App.component
才能工作。
例如:
const routes = [
{ path: ":lingua", component: AppComponent, loadChildren: 'app/main/main.module#MainModule' },
{ path: "", pathMatch: "full", redirectTo: "/en" }
]
这将从主模块加载所有子路由,但允许AppComponent
访问lingua
参数。
然后,您需要:lingua
从子路线中删除该部分
推荐阅读
- sql - 简单的sql(我希望!)
- angular - 嵌套的自定义 FormArray 组件不与具有 FormArrayName 的子表单绑定
- c# - 此会话不支持定位器策略“css 选择器”尝试在 Appium 中获取 EditText 实例时出现异常 - C#
- angular - 有一种方法可以将单选按钮设置为数字类型而不是字符串?
- jpa - 为什么 JPA 要求实体类是非最终的和字段是非最终的
- c++ - 打开文件进行读取时应用程序随机挂起
- git - git commit w/o message 后被困在 vim 调试窗口中
- python - 无法使用 yapf 设置/使用旋钮(谷歌的 Python 格式化程序)
- apache-camel - Weblogic 12.2 中的 Apache Camel LRUCacheFactory 死锁
- r - 如何重新排列行?