How to include Angular services with lazy-loaded standalone component routes?

419 Views Asked by At

I have an Angular 17 application using standalone components, the initial routes are set up like so in 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' },
];

Once the user logs in they are authorized and redirected to /dashboard, and the app-authorized.routes.ts routes are loaded. Here is what that file looks like:

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

I have several services that can only be used once the user logs in, but currently upon inspecting the chunked files Angular loads, all of the services are loaded initially at the login page. Of course this makes sense because they are decorated with

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

Modules of course would make this easy, but since I'm not using modules how do I tell my application to include only certain services along with the lazy-loaded routes, or just any way after the user logs in?

1

There are 1 best solutions below

1
Naren Murali On BEST ANSWER

You need to remove the providedIn: 'root' and you have two options.

  1. Create a module RootModule that will contain the routes of dashboard and settings and then you need to add the services (E.g: TestService) in the providers array of that module!

  2. Create a root component or just in dashboard and settings component. Include the service in the providers array. Please note, that the service instance can only be accessed at the dashboardComponent and its relevant children!

So long story short, If you dont want the services to load during initial login -> add then to the providers array of either a module or a component (preferably root component!)