7

Hello i would like to create routes with language in this format:

www.domain.com/lang/sometimes

Example:

www.domain.com/en/sometimes
www.domain.com/de/sometimes

Is it possible write to route something like:

RouterModule.forChild({
   path: ':lang/sometimes', component: TestComponent
})

Is it possible? How to set to url default language? For example when app starting, set dynamically lang parameter to url.

Thank you for your advices

bluray
  • 1,875
  • 5
  • 36
  • 68

1 Answers1

6

You can do something like this then. You can create two routes, one for default route and another for other Routes.

 RouterModule.forChild([
  { path: 'english/users/sometimes', component: UserComponent, useAsDefault: true },
  { path: ':lang/users/sometimes', component: UserCOmponent }
])

Added: For subscribing to the param:

import { ActivatedRoute } from '@angular/router';

constructior(private route: ActivatedRoute)

ngOnInit(){
this.route.params.subscribe(value => {
    let lang = value['lang']);
    console.log(lang);    

});
}
nirazlatu
  • 983
  • 8
  • 18
  • Thanks and how i get (or set) :lang parameter from url? – bluray Jul 14 '17 at 07:16
  • 1
    For accessing the routes from other components, you can do like this: `this.lang = someLanguage; this.router.navigate([this.lang,'users','sometimes']);` – nirazlatu Jul 14 '17 at 07:20
  • If you need to get the 'lang' parameter from the url. You can subscribe the params on ngOnInit of any component to where you want it. `this.route.params.subscribe(value => { let lang = value['lang'); });` – nirazlatu Jul 14 '17 at 07:23
  • This not working: `this.route.params.subscribe(value => { let lang = value['lang'); });`. In url is /en/sometimes and params are empty. `this.route` is type of `ActivatedRoute`? – bluray Jul 14 '17 at 07:29
  • Can you view my updated comment? Yes, route is of type ActivatedRoute – nirazlatu Jul 14 '17 at 07:42
  • I am sorry. It works. code for get param is running in component. But it is possible that change language in "background"? Outside in component? It is any method which is called always? For example in Module. I dont want change language in each components. – bluray Jul 14 '17 at 10:20