Issue
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?
Solution
You need to remove the providedIn: 'root'
and you have two options.
Create a module
RootModule
that will contain the routes ofdashboard
and settings and then you need to add the services (E.g: TestService) in the providers array of that module!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!)
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.