If a state implements the NgxsOnChanges interface, its ngxsOnChanges method responds when the state is (re)set.
The ngxsOnChanges methods of states are invoked in a topologically sorted order, going from parent to child states. Within these methods, the first parameter is the NgxsSimpleChange object containing the current and previous states.
If a state implements the NgxsOnInit interface, its ngxsOnInit method is invoked after the InitState or UpdateState action has been handled, depending on where the state is registered (root or feature). If your state is provided at the root level, its ngxsOnInit may be called immediately once the ENVIRONMENT_INITIALIZER token is resolved. However, it may also be called asynchronously if you handle the InitState action and have some asynchronous logic.
The ngxsOnInit methods of states are invoked in a topologically sorted order, going from parent to child states. Within these methods, the first parameter is the StateContext, which allows you to access the current state and dispatch actions as usual.
If a state implements the NgxsAfterBootstrap interface, its ngxsAfterBootstrap method will be bound to the APP_BOOTSTRAP_LISTENER, which is resolved after the app has been bootstrapped.
exportinterfaceZooStateModel { animals:string[];}@State<ZooStateModel>({ name:'zoo', defaults: { animals: [] }})@Injectable()exportclassZooStateimplementsNgxsAfterBootstrap {ngxsAfterBootstrap(ctx:StateContext<ZooStateModel>) {console.log('The application has been fully rendered');ctx.dispatch(newGetAnimals()); }}
Lifecycle sequence
After creating the state by calling its constructor, NGXS calls the lifecycle hook methods in the following sequence at specific moments:
Feature States Order of Providers
If you have feature states they need to be registered after the root provideStore has been called:
The APP_INITIALIZER is just a token that references Promise factories. If you've ever used the APP_INITIALIZER token, then you are already familiar with its syntax:
Please refer to this guide to familiarize yourself with its functionality.
APP_INITIALIZER and NGXS
The APP_INITIALIZER token is resolved after NGXS states are registered. This is because they are registered during the resolution of the ENVIRONMENT_INITIALIZER token. Additionally, the ngxsOnInit method on states is invoked before the APP_INITIALIZER token is resolved. Given the following code:
The example provided is for demonstration purposes and will throw an error because the version is not set yet. This occurs because getVersion is called before the version is loaded.
Solution
There are different solutions. Let's look at the simplest. The first solution would be to use the ngxsAfterBootstrap method:
The second solution would be dispatching some SetVersion action right after the version is fetched:
exportclassSetVersion {staticreadonly type ='[Version] Set version';constructor(public version:string) {}}@State<string|null>({ name:'version', defaults:null})@Injectable()exportclassVersionState { @Action(SetVersion)setVersion(ctx:StateContext<string|null>, action:SetVersion):void {ctx.setState(action.version); }}@Injectable({ providedIn:'root' })exportclassConfigService {private http =inject(HttpClient);private store =inject(Store);loadVersion() {returnthis.http.get<string>('/api/version').pipe(tap(version => {this.store.dispatch(newSetVersion(version)); }) ); }}
Summary
In conclusion, the ngxsOnInit method is useful when you need to set some calculated values on the state with access to dependency injection within the state class, but before the app is bootstrapped. This allows components to pick up available data.