代码之家  ›  专栏  ›  技术社区  ›  Chris Barr

如何将Angular服务包含在延迟加载的独立组件路由中?

  •  0
  • Chris Barr  · 技术社区  · 2 年前

    我有一个使用独立组件的Angular 17应用程序,初始路由设置如下 app.routes.ts

    export const appRoutes: Array<Route> = [
      { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
      {
        path: 'login',
        component: LoginComponent,
        title: 'Login',
      },
      {
        path: '',
        canActivateChild: [AuthGuard],
        loadChildren: () => import(`./app-authorized.routes`).then((r) => r.appAuthorizedRoutes),
      },
      { path: '**', redirectTo: '/dashboard' },
    ];
    

    用户登录后,他们将被授权并重定向到 /dashboard ,以及 app-authorized.routes.ts 路线已加载。以下是该文件的外观:

    export const appAuthorizedRoutes: Array<Route> = [
      {
        path: 'dashboard',
        component: DashboardComponent,
        canActivate: [AuthGuard],
        title: 'Dashboard',
      },
      {
        path: 'settings',
        component: SettingsComponent,
        canActivate: [AuthGuard],
        title: 'Settings',
      },
      //etc...
    ];
    

    @Injectable({
      providedIn: 'root',
    })
    

    0 回复  |  直到 2 年前
        1
  •  1
  •   Naren Murali    2 年前

    providedIn: 'root'

    1. RootModule dashboard

    2. 创建根组件或仅在仪表板和设置组件中创建。将服务包含在提供者数组中。请注意,服务实例只能在dashboardComponent及其相关子级上访问!

    长话短说,如果您不希望在初始登录时加载服务->然后添加到模块或组件(最好是根组件!)的提供者数组中

    推荐文章