在角度9中进行路由的延迟加载

时间:2020-10-01 10:31:24

标签: javascript angular

我尝试使用登录组件进行延迟加载。

所以我有一个这样的AccountModule:

@NgModule({
  declarations: [LoginComponent, RegisterComponent],
  imports: [
    CommonModule,
    AccountRoutingModule
  ]
})
export class AccountModule { }

和我的App-routing.module看起来像这样:

const routes: Routes = [
  {path: 'account', loadChildren: () => import('./account/account.module')
.then(mod => mod.AccountModule)},

{ path: '**', redirectTo: 'not-found', pathMatch: 'full' }
];

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

,登录组件如下所示:

<div class="d-flex justify-content-center mt-5">
  <div class="col-3">
    <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
      <div class="text-center mb-4">
        <h1 class="h3 mb-3 font-weight-normal">Login</h1>
      </div>

      <app-text-input formControlName="email" [label]="'Email Address'"></app-text-input>
      <app-text-input formControlName="password" [label]="'Password'" [type]="'password'"></app-text-input>

      <button [disabled]="loginForm.invalid" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
  </div>
</div>

但是如果我想转到:http:// localhost:4200 / account / login。可以回溯到http:// localhost:4200。

那我要改变什么?

谢谢

AccountRoutingModule:

const routes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent}
];

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

2 个答案:

答案 0 :(得分:1)

您在RouterModule.forRoot中使用了AccountRoutingModule,可能将loginregister注册到了根目录。您只能在forRoot中使用AppModule,在其他地方使用RouterModule.forChild

答案 1 :(得分:0)

您只需要更改您的 AccountRoutingModule

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

enter image description here