Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing & Modules

I have the following routing configuration in my app:

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRouting,

    // Feature Modules
    CoreModule,
    AuthModule,
    AdminModule,
    SharedModule
  ],
  bootstrap: [AppComponent]
})

app.routing.ts

const routes: Routes = [
  { path: '', redirectTo: 'admin', pathMatch: 'full' },
  { path: 'admin', loadChildren: () => AdminModule }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
  ],
  exports: [RouterModule]
})

admin.module.ts

@NgModule({
  declarations: [
    AdminComponent
  ],

  imports: [
    CommonModule,
    FormsModule,
    UserModule,

    AdminRouting,
    SharedModule
  ],

  providers: [
    UserService
  ]
})

admin.routing.ts

const routes: Routes = [
  { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [
    { path: 'users', loadChildren: () => UserModule }
  ]}
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

user.module.ts

@NgModule({
  declarations: [
    UserComponent,
    UserManageComponent,
    UserListComponent
  ],

  imports: [
    CommonModule,
    FormsModule,

    UserRouting,
    SharedModule
  ]
})

user.routing.ts

const routes: Routes = [
  { path: '', component: UserComponent, children: [
    { path: '', component: UserListComponent },
    { path: 'new', component: UserManageComponent },
    { path: ':id/edit', component: UserManageComponent }
  ]},
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

And there's the problem:

What I expected my application routing does:

/users => not a valid route
/users/new => not a valid route

/admin/users => valid route
/admin/users/new => valid route
/admin => valid route (should render AdminComponent)

I don't know why, but if I enter /users, the applications render UserComponent, what is not the behavior I would like to.

I would like UserComponent to be accessed only from /admin/users.

Does anybody could explain me why?

like image 611
Guilherme Chiara Avatar asked May 17 '26 20:05

Guilherme Chiara


2 Answers

Try this to see:

admin.routing.ts

const routes: Routes = [
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard], 
        children: [{ path: 'users', loadChildren: () => UserModule }]}
];
like image 167
Blockchain Nerd Avatar answered May 20 '26 16:05

Blockchain Nerd


Did you already try to move AppRouting imports to end of imports array as is suggested here?

like image 29
Hows Leal Avatar answered May 20 '26 16:05

Hows Leal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!