0

I hate auth.guard.ts :

import { Injectable } from '@angular/core';
import {  CanActivateChild, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { AuthService } from '../services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivateChild {
  constructor(public auth: AuthService, public router: Router) {}
  canActivateChild(): Observable<boolean> {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['b2b/auth/login']);
      return of(false);
    }
    return of(true);
  }
}

Which returns to login page if person is not LoggedIn. While i code on local machine, it works fine as it should. The problem appears when i build my project with server side, after each page "Refresh" "F5" login page shows up for about 1 second and then redirects to a page where i was. The url always stays the same.

How to fix this glitch ?

Example from other question without any answers : Angular 2+ guard has strange behavior on page refresh (I use express for ssr instead of .net)

  public isAuthenticated(): boolean {
    if (typeof window !== 'undefined') {
      const token = localStorage.getItem(this.AUTH_TOKEN);
      if (!token) {
        return false;
      }
      return !this.tokenExpired(token);
    }
  }
Devla
  • 326
  • 4
  • 19

1 Answers1

0

During the SSR build user are not login and !token conditon is consider true and it render the login route

Solution: Detect whether the current runtime is the browser or the server with the help of isPlatformBrowser() and isPlatformServer()

constructor(public auth: AuthService, public router: Router,
  @Inject(PLATFORM_ID) private platformId: Object,) { }

  canActivateChild(): Observable < boolean > {

    if(isPlatformBrowser(this.platformId)) {

      if (!token) {return false;}  }

    if (isPlatformServer(this.platformId)) {}

    return of(true);
  }
ubaid iftikhar
  • 231
  • 4
  • 6