Home > Net >  Is there a way to use one variable for all routes in Angular?
Is there a way to use one variable for all routes in Angular?

Time:04-15

I have a project where I got a task to change the language in the URL and render it, for example, right now my URL looks like this /home/component/new and I need it to be /:language/home/component/new My routes page looks like this

const routes: Routes = [
  {
    path: 'home/:searchKey/:page',
    component: HomeComponent
  },
  {
    path: '/music/:artist',
    component: MusicComponent,
  },
  {
    path: '/video/:name',
    component: VideoComponent,
  },
];

I know I can do it if I make a variable and change it like this.

const routes: Routes = [
  {
    path: ':language/home/:searchKey/:page',
    component: HomeComponent
  },
  {
    path: ':language/music/:artist',
    component: MusicComponent,
  },
  {
    path: ':language/video/:name',
    component: VideoComponent,
  },
];

But is there a way to declare this variable and use it automatically in every route I ever make without having to write :language for every new route?

CodePudding user response:

Seems like you should instead use the Angular i18N tool, which is made exactly for this kind of need.

But to answer you


const routes: Routes = [
  {
    path: ':lang',
    children: [
      { path: 'home', component: HomeComponent },
      { path: 'music', component: MusicComponent },
      // ...
    ]
  }
];

  • Related