0

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);
  }

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Worked, I had to in this case create a new component between app component and my child components and used that as the component for :lang, but otherwise works good. thanks
it was a pleasure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.