Angular Ngrx Store and APP_Initialiser

Discussão em 'Angular' iniciado por Stephen Cossgrove, Dezembro 10, 2024.

  1. Hi I really am struggling with an issue.

    We currently are using nrgx Store to essentially store data client side regarding information about the client side application. This is working great.

    However we are finding that when users are navigate off the site then back onto it it is remembering previous data.

    Therefore I'm trying to reset the store information on application start using an APP_INITALIZER.

    My problem is that the intializer is async an therefore my calls to reset the ngrx store are starting but not finishing before the application is fully initialized.

    Here is what i have:

    import { Injectable } from '@angular/core';
    import { Store } from '@ngxs/store';
    import { environment } from 'src/environments/environment';
    import { ResetApplicationStateModel } from 'src/app/modules/state/application-state.actions';

    @Injectable({ providedIn: 'root' })
    export class AppStateInitializerService {

    isDevelopment = !environment.production;

    constructor(private store: Store) {}

    async initialize(): Promise<void> {
    let loggingPrefix = 'app-state-initialiser.service::initializeApp - ';

    return new Promise<void>((resolve, reject) => {
    if (this.isDevelopment) {
    console.log(loggingPrefix + 'start of method');
    }

    //do your initialisation stuff here
    try {
    // Wait for the action to complete
    if (this.isDevelopment) {
    console.log(loggingPrefix + 'before ResetApplicationStateModel');
    }

    this.store.dispatch(new ResetApplicationStateModel());
    if (this.isDevelopment) {
    console.log(loggingPrefix + 'after ResetBookingReviewStateModel');
    }

    if (this.isDevelopment) {
    console.log(loggingPrefix + 'end of method');
    }
    } catch (error) {
    console.error(loggingPrefix + 'Action failed:', error);
    }

    // Set the wait loop
    setTimeout(() => {
    if (this.isDevelopment) {
    console.log(loggingPrefix + 'end of method');
    }
    resolve();
    }, 1000);
    });
    }
    }


    And in the app.module.ts

    export function initializerStateService(myInitializerService:
    AppStateInitializerService) {
    return (): Promise<any> => {
    return myInitializerService.initialize();
    }
    }


    Can anyone help?

    Continue reading...

Compartilhe esta Página