Angular 17 - SSR 独立 - 具有异步的路由 FactoryProvider - NG04014

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

简介

您好,我正在尝试配置我的角度路由器并根据我们是否经过身份验证向其传递不同的路由。

这是我执行此操作的代码:

app.routes.ts

export const authenticatedRoutes: Routes = [
  {
    path: 'test',
    component: DashboardPage,
  },
  {
    path: '**',
    redirectTo: 'test'
  }
];

export const unauthenticatedRoutes: Routes = [
  {
    path: 'test',
    component: HomePage,
  },
  {
    path: '**',
    redirectTo: 'test'
  }
];

export const provideRoutes = () => {
  const provider: Provider[] = [{
    provide: ROUTES,
    useFactory: async (oidcSecurityService: OidcSecurityService) => {
      const { isAuthenticated } = await firstValueFrom(oidcSecurityService.checkAuth())
      if (isAuthenticated) return authenticatedRoutes
      return unauthenticatedRoutes
    },
    multi: true
  }]
  return makeEnvironmentProviders(provider)
}

app.config.ts

import { provideRoutes } from '@/configurations'

export const appConfig: ApplicationConfig = {
  providers: [
    provideRoutes(),
    // others providers...
  ]
};

研究

当我运行

"ng build --watch --configuration development"
时,我收到此错误

发生未处理的异常:NG04014:路由''的配置无效。必须提供以下其中一项:component、loadComponent、redirectTo、children 或 loadChildren

问题来自异步工厂,这段代码可以工作:

export const provideRoutes = () => {
  const provider: Provider[] = [{
    provide: ROUTES,
    useFactory: () => {
      return unauthenticatedRoutes
    },
    multi: true
  }]
  return makeEnvironmentProviders(provider)
}

但我不知道如何解决这个问题。你知道我应该做什么吗?

angular angular-routing angular-providers angular-standalone-components angular-ssr
1个回答
0
投票

Angular 不支持异步提供程序(参见问题)。

您可能正在寻找路线守卫,更具体地说:

CanActivate

你的守护者

export const yourGuardFunction: CanActivateFn = (
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot) => {
      // your  logic goes here
  }

您的路线:

{
  path: '/your-path',
  component: YourComponent,
  canActivate: [yourGuardFunction],
}
© www.soinside.com 2019 - 2024. All rights reserved.