After creating the state by calling its constructor, NGXS calls the lifecycle hook methods in the following sequence at specific moments:
Hook
Purpose and Timing
ngxsOnChanges()
Called beforengxsOnInit() and whenever state changes.
ngxsOnInit()
Called once, after the firstngxsOnChanges() and before the APP_INITIALIZER token is resolved.
ngxsAfterBootstrap()
Called once, after the root view and all its children have been rendered.
ngxsDataDoCheck()
Called afterngxsAfterBootstrap() and called every time a state is reinitialized after a state reset.
ngxsDataAfterReset()
Called every time afterreset()
ngxsDataDoCheck and ngxsDataAfterReset
@StateRepository()@State<Customer[]>({ name:'customers', defaults: []})@Injectable()classCustomersStatesextendsNgxsDataRepository<Customer[]> implementsNgxsDataDoCheck,NgxsDataAfterReset {private subscription:Subscription;constructor(private customer:CustomerService) {super(); }/** * @description: * This method guarantees that it will be called after the application is rendered * and all services of the Angular are loaded, so you can subscribe to the necessary * data streams (any observables) in this method and unsubscribe later in the method `ngxsDataAfterReset` */publicngxsDataDoCheck():void {console.log(this.isInitialised); // trueconsole.log(this.isBootstrapped); // truethis.subscription =this.customer.events.subscribe((e) =>console.log(e)); }publicngxsDataAfterReset():void {this.subscription?.unsubscribe(); }}
ngxsOnChanges, ngxsOnInit and ngxsAfterBootstrap
@StateRepository()@State({ name:'counter', defaults:0})@Injectable()classCounterStateextendsNgxsDataRepository<number> implementsNgxsOnChanges,NgxsOnInit,NgxsAfterBootstrap {publicngxsOnChanges():void {super.ngxsOnChanges(); // be sure to call the parent method// your logic }publicngxsOnInit():void {super.ngxsOnInit(); // be sure to call the parent method// your logic }publicngxsAfterBootstrap():void {super.ngxsAfterBootstrap(); // be sure to call the parent method// your logic }}