首页 > 解决方案 > 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);
  }

标签: angularparametersangular6angular-routing

解决方案


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.


推荐阅读