TorSen
TorSen

Reputation: 149

Angular router prefix

I have a bunch of components that use router with absolute paths for navigation on some actions.

Lets consider i have the EntityComponent with some action that navigates to /otherEntity/* urls

That works fine.

For now i added another one top level component and configured the router with the following url: localhost/PREFIX/ to target that component, also i added the existing routes as the childs.

I can access the existing components by the localhost/prefix/entities but the navigation of this components is broken. When i perform actions i navigated to /otherEntity/ instead of /prefix/otherEntity

Is there any way to solve it? I use relative paths for some of the components when i can, but there are some cases when i can't do that way.

Main routes:

const routes: Routes = [
          {
            path: '',
            component: AppComponent,
            children: [
              applicationRoutes
            ]
          },
          {
            path: 'prefix/',
            component: AppPrefixComponent,
            children: [
              applicationRoutes
            ],
          },
]

Application lvl routes:

export const applicationRoutes: Routes = 
    [
            {
              path: 'entities',
              component: EntityComponent
            },
            {
              path: 'anotherEntity',
              component: AnotherEntityComponent,
            },
    ]

Navigation sample:

export class EntityComponent {

   navigateToAnotherEntity() {
      this.router.navigate('/anotherEntity');
   }
}

Upvotes: 0

Views: 1203

Answers (1)

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

I mean something like this

export function applicationRoutes(prefix: string = ''): Routes {
  return  [
            {
              path: 'entities',
              component: EntityComponent,
              data: {prefix: prefix}
            },
            {
              path: 'anotherEntity',
              component: AnotherEntityComponent,
              data: {prefix: prefix}
            },
    ]
}
const routes: Routes = [
          {
            path: '',
            component: AppComponent,
            children: [
                 applicationRoutes('')
            ]
          },
          {
            path: 'prefix/',
            component: AppPrefixComponent,
            children: [
              applicationRoutes('prefix')
            ],
          },
]

and in component.ts you can get the data from router

export class Component implements OnInit {
prefix = ''
constrcutor(private router: Router) {
   this.prefix = this.router.snapshot.data['prefix']
}
   navigateToAnotherEntity() {
      this.router.navigate(`${this.prefix}/anotherEntity`);
   }

}

Upvotes: 1

Related Questions