有 2 个模块具有相同的路径但具有不同的模板(main 和 auth)。模块加载关于用户是否通过身份验证是必要的。不幸的是,它不是这样工作的。
有代码
app-routing.module.ts
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthService } from './core/services/auth.service';
var authService = new AuthService()
const routes: Routes = [
{path: '', loadChildren:() => authService.isAuth ? import('./modules/main/main.module').then(m => m.MainModule) : import('./modules/auth/auth.module').then(m => m.AuthModule)}
];
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule]
})
export class AppRoutingModule { }
main.router.ts
import { NgModule } from '@angular/core';
...
const routes = [
{path: '', component: MainComponent, children: [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: 'dashboard', component: MainPageComponent},
{path: 'payments', component: PaymentPageComponent},
{path: 'profile', component: ProfileComponent},
{path: 'cards', component: CardsComponent},
{path: 'accounts', component: AccountsComponent},
{path: 'loans', component: LoansComponent},
{path: 'deposits', component: DepositsComponent},
{path: 'extracts-and-reports', component: ExtractsAndReportsComponent},
{path: 'payroll', component: PayrollComponent},
{path: 'settings', component: SettingsComponent},
{path: 'confirm', component: PaymentAccessComponent},
{path: 'mailbox', component: MailboxComponent},
{path: '**', component: PageNotFoundComponent}
]}
]
@NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [
RouterModule
],
declarations: [],
providers: [],
})
export class MainRouter { }
auth.router.ts
import { NgModule } from '@angular/core';
...
const routes = [
{path: '', component: AuthComponent, children: [
{path: '', redirectTo: 'login', pathMatch: 'full'},
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent}
]}
]
@NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [
RouterModule
],
declarations: [],
providers: [],
})
export class AuthRouter { }
Angular 路由器有一个名为resetConfig()的方法,它允许您替换路由配置。您在应用加载时使用一种配置,当您检测到用户已通过身份验证时,您可以将其替换为加载其他模块的配置。
所以基本上你会有两个路由配置:
const routesDefault: Routes = [
{path: '', loadChildren:() => import('./modules/auth/auth.module').then(m => m.AuthModule)}
];
const routesAuth: Routes = [
{path: '', loadChildren:() => import('./modules/main/main.module').then(m => m.MainModule)}
];
@NgModule({
imports: [
RouterModule.forRoot(routesDefault)
],
...
然后在您的代码中的某处,每当您检测到用户已通过身份验证时,请执行以下操作:
router.resetConfig(routesAuth);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句