如何在 Angular 16 中使用路由 useFactory 方法

问题描述 投票:0回答:1

我正在使用 Angular 16 独立路线,我想在其中处理导航

  1. 医生
  2. 医院

两者都应该有/登录后。

如下是我的路线

app.routes.ts

{
        path: '', //  Hospital portal
        loadChildren: () => import('@pages/hospital/hospital.module'),
        canMatch: [authGuard({ requiresAuthentication: true, role: accountType.hospital })],
    },
    {
        path: '', //  Dcotor portal
        loadChildren: () => import('@pages/doctor/doctor.module'),
        canMatch: [authGuard({ requiresAuthentication: true, role: accountType.doctor })],
    },

app.config.ts


export const appConfig: ApplicationConfig = {
    providers: [
        provideRouter(routes, withComponentInputBinding(), withPreloading(SelectivePreloadingStrategyService)),
        provideHttpClient(withInterceptors([serverErrorInterceptor, jwtInterceptor])),
        provideAnimations(), // required animations providers
        provideToastr(), // Toastr providers
        .....,
        importProvidersFrom(
            TranslateModule.forRoot({
                isolate: true,
                loader: {
                    provide: TranslateLoader,
                    useFactory: createTranslateLoader,
                    deps: [HttpClient],
                },
            }),
        ),
        { provide: TitleStrategy, useClass: TemplatePageTitleStrategy },
        {
            provide: ROUTES,
            useFactory: () => {
                let authService = inject(AuthService);
                let customizedRoutes: Routes = [];
                customizedRoutes.push({
                    path: '',
                    canMatch: [authGuard({ requiresAuthentication: true })],
                    loadChildren: () =>
                        authService.hasRole() == 3
                            ? import('@pages/hospital/hospital.module')
                            : import('@pages/doctor/doctor.module'),
                });

                return [...customizedRoutes, ...routes];
            },
            multi: true,
            deps: [AuthService]
        },
    ],
};

我的canMatch守卫


export const authGuard = (options: AuthGuardOptions = defaultAuthGuardOptions()): CanMatchFn => {
    return (_: Route, segments: UrlSegment[]) => {
        const authService = inject(AuthService);
        const router = inject(Router);
        if (options.requiresAuthentication && authService.isAuthenticated) {
            return true
        }
        return options.requiresAuthentication
            ? router.createUrlTree(['/auth/login'], {
                  queryParams: {
                      returnUrl: segments.map((s) => s.path).join('/'),
                  },
              })
            : router.createUrlTree(['/']);
    };

我尝试过 Angular 14 并找到了 Angular 14 的解决方案

https://levelup.gitconnected.com/angular-dynamic-routing-299c04ca75b1

https://netbasal.com/conditionally-load-a-module-using-angular-router-aff022923850

但在 Angular 16 中我卡住了如何使用 useFactory 方法

我也读过这篇文章如何在角度中使用useFactory根据某些条件延迟加载模块?但是如何在16中实现,我正在寻找

angular authentication routes guard
1个回答
0
投票

我遇到了同样的场景,当我将路由器作为provideRouter中的空数组[]时,它工作得很好。

export const appConfig: ApplicationConfig = {
providers: [
   {
     provide: ROUTES,
     useFactory: appRoutesFactory,
     deps: [ProjectService],
     multi: true,
   },
   provideRouter([], withEnabledBlockingInitialNavigation()),
   ...
]
© www.soinside.com 2019 - 2024. All rights reserved.