简体   繁体   English

AppComponent中的Angular 6路由URL字符串参数

[英]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. 我的路由器出口位于我的AppComponent中。 Now the AppComponent sets my html template for the entire app and it also has language switching buttons. 现在,AppComponent为整个应用程序设置了我的html模板,并且还具有语言切换按钮。

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. 如果尝试在AppComponent中访问它们,则该值为null。 If I do the exact same code in Home the value is found and works. 如果我在Home中执行完全相同的代码,则将找到该值并起作用。 But I need the params in the AppComponent so that doesn't help me. 但是我需要AppComponent中的参数,所以对我没有帮助。

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. 现在,我在路由中只有1个示例,但是在应用程序中我将有很多路由,所有路由都应以lang参数开头。

I tried researching but I can't seem to find any help. 我尝试研究,但似乎找不到任何帮助。 All examples I tried don't work when put in the AppComponent. 当我放入AppComponent中时,我尝试的所有示例均无效。

EDIT: Here is snippit of my AppComponent 编辑:这是我的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. 那么您应该在所有子级中都具有访问权限,方法是在ngOnInit中将其从AppComponent提取到服务组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM