How to retrieve a value from ngx-cookie-service before the app loads?

Discussão em 'Angular' iniciado por e Res, Novembro 5, 2024.

  1. e Res

    e Res Guest

    I'm encountering an issue when a user reloads the page. On app startup, there’s a brief delay (100-400ms) needed to retrieve a value from the cookie. During this time, the user is briefly redirected to the login page, but once the cookie value is retrieved, the app navigates back to the home page. I've attached my HTML and TypeScript code that seems to be causing this problem. How can I implement this: first load the cookie, then navigate to the login or home page?

    // app.component.html
    <div id="app-main-container" style="height: 100vh; overflow: hidden;" *ngIf="globals.isAuthenticated; else login">
    <app-side-nav></app-side-nav>
    <div class="main">
    <app-nav-bar></app-nav-bar>
    <router-outlet></router-outlet>
    <app-footer></app-footer>
    </div>
    </div>


    TS file - Globals

    // globals
    get isAuthenticated(): boolean {
    return !!(this.auth)
    }

    get auth() {
    if (this._auth != null) {
    return this._auth;
    } else {
    const authJson = this.cookieService.get('auth');

    if (!authJson) {
    console.warn("Auth cookie is missing");
    }
    // Attempt to parse only if loggedUserJson is not null or undefined
    const data = authJson ? JSON.parse(authJson) : null;

    if (data) {
    this._auth = data;
    return this._auth;
    } else {
    this._auth = null;
    return this._auth;
    }
    }
    }

    constructor(
    private cookieService: CookieService
    ) {}

    Continue reading...

Compartilhe esta Página