angular - Angular 6 Route URL String Parameter in AppComponent
问题描述
I want to have all my routes start with a language parameter like so:
/en/home
/fr/home
My router-outlet is located in my AppComponent. Now the AppComponent sets my html template for the entire app and it also has language switching buttons.
Currently I have the following routes:
const routes: Routes = [
{ path: ':lang/home', component: HomeComponent },
{ path: '', redirectTo: 'en/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
If I try to access them in my AppComponent the value is null. If I do the exact same code in Home the value is found and works. But I need the params in the AppComponent so that doesn't help me.
Right now I only have 1 example in the routes but I will have many routes in the application, and ALL of them should start with the lang parameter.
I tried researching but I can't seem to find any help. All examples I tried don't work when put in the AppComponent.
EDIT: Here is snippit of my AppComponent
constructor(private translate: TranslateService, private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.translate.setDefaultLang('en');
this.route.paramMap.subscribe(params => {
const lang = params.get('lang');
console.log(lang);
if (lang != null && (lang === 'fr' || lang === 'en')) {
this.switchLanguage(lang);
}
});
}
switchLanguage(language: string) {
this.translate.use(language);
if (language === 'en') {
this.isEnglish = true;
} else {
this.isEnglish = false;
}
console.log('switching to: ' + language);
}
解决方案
change it to something like this:
{ path: ':lang', component: AppComponent, children: [
{ path: 'home', component: HomeComponent },
]},
{ path: '', redirectTo: 'en/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
then you should have access in all childs by fetching it in the ngOnInit from the AppComponent to an service component.
推荐阅读
- variables - WinBUGS 中未初始化的变量和#Bugs:dic.set 无法执行(灰显)问题
- php - Symfony 控制器功能测试中的 $this->getUser() 返回 null
- python - 检查元组列表的顺序
- amazon-web-services - 如何像 SQS 一样使用 Kinesis?
- javascript - Window.whatever 未定义
- c# - 如何格式化 Dynamics 365 c# 插件的 LINQ 查询
- typescript - `keyof T`和`Extract有什么区别
` 使用扩展泛型时? - python - 如何在没有循环和 if-else 的情况下打印整个圣诞节十二天的歌词
- ruby-on-rails - Rails rename_column 更改列的类型
- rhel - 将 chrony.conf 文件设置为“服务器”而不是“池”