3

I am facing issue with NGXS in Angular 18 with almost all standalone components. I have applied lazy loading for components. While I am switching from roles page to users page it is dispatching/calling roles actions which is in ngOnInit of the roles component. similarly when switching from users page to roles page same thing is happening.

In routes file

export const routes: Routes = [
  { path: 'login', component: LoginComponent, canActivate: [loginGuard] },
  {
    path: '',
    component: AppLayoutComponent,
    canActivate: [authGuard],
    children: [
      {
        path: '',
        redirectTo: '/dashboard',
        pathMatch: 'full',
      },
      {
        path: 'members/roles',
        canActivate: [authGuard],
        loadComponent: () => import('./features/members/roles/roles.component').then(m => m.RolesComponent),
        providers: [provideStates([RolesState])]
      },
      {
        path: 'members/users',
        canActivate: [authGuard],
        loadComponent: () => import('./features/members/users/users.component').then(m => m.UsersComponent),
        providers: [provideStates([UserState])]
      },
      
    ],
  },
];

In appConfig file

export const appConfig: ApplicationConfig = {
  providers: [
    MessageService,
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    importProvidersFrom(AppLayoutModule),
    provideHttpClient(),
    provideStore([]),
    withNgxsReduxDevtoolsPlugin()
  ],
};

Tried with separate route file for members.

2
  • I guess that this can also be attributed to memory leaks. Is the number of dispatches increasing when you switch between the components?
    – OctavianM
    Commented Jul 31 at 19:11
  • A Stackblitz reproduction would be super helpful in debugging this issue. Commented Jul 31 at 19:38

1 Answer 1

0

From the Route Providers Docs we can see it's created as a environment provider (which exists through the lifecycle of the application).

providers (EnvironmentProviders | Provider)[]

A Provider array to use for this Route and its children.

The Router will create a new EnvironmentInjector for this Route and use it for this Route and its children. If this route also has a loadChildren function which returns an NgModuleRef, this injector will be used as the parent of the lazy loaded module.


So you can move the providers to the providers array of the component and it will get destroyed. Currently when you use in providers array, it exists even after the route gets destroyed.

Not the answer you're looking for? Browse other questions tagged or ask your own question.