Home > OS >  Angular routing for the component
Angular routing for the component

Time:11-09

I watch videos on YouTube on routing in Angular. The app-routing.module file.ts, I omit the imports

const routes: Routes = [
  {
    path: '', component: MainLayoutComponent, children: [
      {path: '', redirectTo: '/', pathMatch: 'full'},
      {path: '', component: MainPageComponent},
      {path: 'product/:id', component: ProductPageComponent},
      {path: 'cart', component: CartPageComponent}
    ]
  },
  {
    path: 'admin', loadChildren: './admin/admin.module#AdminModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Next, a separate admin.module is created there.ts, which implements another routing

@NgModule({
    declarations: [
        AdminLayoutComponent,
        LoginPageComponent,
        DashboardPageComponent,
        AddPageComponent,
        EditPageComponent,
        OrdersPageComponent,

    ],
    imports:[
        CommonModule,
        RouterModule.forChild([
            {
                path: '', component: AdminLayoutComponent, children: [
                    {path: '', redirectTo: '/admin/login', pathMatch: 'full'},
                    {path: 'login', component: LoginPageComponent},
                    {path: 'dashboard', component: DashboardPageComponent},
                    {path: 'add', component: AddPageComponent},
                    {path: 'orders', component: OrdersPageComponent},
                    {path: 'product/:id/edit', component: EditPageComponent},
                ]
            }
        ])
    ],
    exports: [RouterModule]
})

export class AdminModule{
    
}

According to the lesson, when he goes to the address localhost:4200/admin, he is thrown to the page localhost:4200/admin/login. And throws me to localhost:4200

What did I miss?

CodePudding user response:

Your app-routing.module.ts should be like this:

const routes: Routes = [
  {
    path: '', component: MainLayoutComponent, children: [
      {path: '', redirectTo: '/', pathMatch: 'full'},
      {path: '', component: MainPageComponent},
      {path: 'product/:id', component: ProductPageComponent},
      {path: 'cart', component: CartPageComponent}
    ]
  },
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module#AdminModule').then(m => m.AdminModule)
  }
];

admin.module.ts:

const routes: Routes = [
{
   path: '', component: AdminLayoutComponent, children: [
     {path: '', redirectTo: 'login', pathMatch: 'full'},
     {path: 'login', component: LoginPageComponent},
     {path: 'dashboard', component: DashboardPageComponent},
     {path: 'add', component: AddPageComponent},
     {path: 'orders', component: OrdersPageComponent},
     {path: 'product/:id/edit', component:EditPageComponent},
   ]
}];

Take a look at the documentation: https://angular.io/guide/lazy-loading-ngmodules

  • Related