LogoLogo
v3.7
v3.7
  • README
  • Getting Started
    • Why
    • Installation
  • Concepts
    • Introduction
    • Store
    • Actions
    • State
    • Select
  • Advanced
    • Action Handlers
    • Actions Life Cycle
    • Cancellation
    • Composition
    • Error Handling
    • Ivy Migration Guide
    • Lazy Loading
    • Life-cycle
    • Mapped Sub States
    • Meta Reducers
    • Optimizing Selectors
    • Options
    • Shared State
    • State Token
    • State Operators
    • Sub States
  • Recipes
    • Authentication
    • Caching
    • Component Events from NGXS
    • Debouncing Actions
    • Dynamic Plugins
    • Immutability Helpers
    • Module Federation
    • Style Guide
    • Unit Testing
    • RxAngular Integration
  • Snippets
    • State Operators
  • Plugins
    • Introduction
    • CLI
    • Logger
    • Devtools
    • Storage
    • Forms
    • Web Socket
    • Router
    • HMR
  • NGXS Labs
    • Introduction
  • Community
    • FAQ
    • Resources
    • Contributors
    • Contributing
    • Sponsors
  • Changelog
Powered by GitBook
On this page
  1. Advanced

Lazy Loading

Stores can be lazy-loaded easily by importing the NgxsModule using the forFeature method. All the other syntax for how you import and describe them are the same. For example:

@NgModule({
  imports: [NgxsModule.forFeature([LazyState])]
})
export class LazyModule {}

It's important to note when lazy-loading a store, it is registered in the global state so this state object will now be persisted globally. Even though it's available globally, you should only use it within that feature module so you make sure not to create dependencies on things that could not be loaded yet.

How are feature states added to the global state graph? Assume you've got a ZoosState:

@State<Zoo[]>({
  name: 'zoos',
  defaults: []
})
@Injectable()
export class ZoosState {}

And it's registered in the root module via NgxsModule.forRoot([ZoosState]). Assume you've got a feature offices state:

@State<Office[]>({
  name: 'offices',
  defaults: []
})
@Injectable()
export class OfficesState {}

You register this state in some lazy-loaded module via NgxsModule.forFeature([OfficesState]). After the lazy module is loaded - the global state will have such signature:

{
  zoos: [],
  offices: []
}

You can try it yourself by invoking store.snapshot() and printing the result to the console before and after the lazy module is loaded. .

PreviousIvy Migration GuideNextLife-cycle

Last updated 2 years ago