Search code examples
angularangular-routing

angular routing to component without entering full url


When routing to a child module in my angular application, I can route to it without entering the full URL & i'm not sure why

E.G. I want to route to admin/garage/1, which works, but if I route to garage/1, it takes me to the same place (which I dont expect it to)

localhost:4200/admin/garages/1 takes me to ViewGarageComponent, but localhost:4200/garages/1 also takes me there, I dont expect localhost:4200/garages/1 to take me there as it is in the admin/ child routes

admin module router (i expect all these routes to be admin/)

const adminRoutes: Routes = [
  { path: 'admin', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: AdminComponent },
  { path: 'garages', component: GarageListComponent },
  { path: 'garage/:garageId', component: ViewGarageComponent },
];
@NgModule({
  imports: [RouterModule.forChild(adminRoutes)],
  exports: [RouterModule],
})
export class AdminRoutingModule {}

admin module

@NgModule({
  imports: [
    CommonModule,
    AdminRoutingModule,
    MatProgressSpinnerModule,
    MatToolbarModule,
    MatIconModule
  ],
  declarations: [
    AdminComponent,
    ViewGarageComponent,
    CreateGarageComponent,
    GarageListComponent,
    HeaderComponent
  ]
})
export class AdminModule { }

app module router

const routes: Routes = [
  { path: '', redirectTo: '/sign-in', pathMatch: 'full' },
  { path: 'sign-in', component: SignInComponent },
  { path: 'register-user', component: SignUpComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'schedule', component: SyncScheduleComponent, canActivate: [AuthGuard] },
  { path: 'forgot-password', component: ForgotPasswordComponent },
  { path: 'verify-email-address', component: VerifyEmailComponent },
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule), canActivate: [AdminAuthGuard]
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})

Solution

  • I found the answer, I added AdminModule as an import in AppModule which I belive was causing it to use both routes, admin/garage/1, as well as /garage/1.

    Once I removed AdminModule from AppModule the issue was resolved