Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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
  ) {}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may have SSR enabled, so you can try the below fix, which shows a loader when SSR loads login page and then navigates to the main page.

The @defer shows the login page when you are in browser and the @placeholder will show a loading screen when you are in server.

Deferrable Views – Angular.dev

@if(isBrowser) {
   <!-- Login HTML goes here -->
} @placeholder {
   Loading... <!-- replace with some nice spinner HTML -->
}

Also noticed that there is a ngx-cookie-service-ssr, maybe this can help with this SSR problem. Assuming you are using SSR.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading