Search code examples
angularguardcanactivate

Using angular 2 guard. How to Keep user logged in when refreshing the page?


Here is my angular code for routing in app.module.ts file.

const appRoutes: Routes = [
{path: '', component: LoginformComponent},
  {path: 'dashboard', component: DashboardComponent, canActivate: [AuthenticationGuard]},
  {path: 'user', children: [
      {path: '', component: UserComponent},
      {path: ':id', component: UserdetailComponent}
    ], canActivate: [AuthenticationGuard]
  },
  {path: '**', component: NotfoundComponent}
];

And following code represent the guard file.

export class AuthenticationGuard implements CanActivate {

  constructor(private user: UserService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (! this.user.getUserLoggedIn()) {
      this.router.navigate(['/']);
    }
    return this.user.getUserLoggedIn();
  }
}

Guard works fine when Im logged in as a user. But in case of refreshing it log me out. I want a method to keep me logged in the system even after refreshing the page?

This is the user service.ts file,

@Injectable()
export class UserService {
  private isUserLoggedIn: boolean;
  private username: string;

  constructor() {
    this.isUserLoggedIn = false;
  }

  setUserLoggedIn(username) {
    this.isUserLoggedIn = true;
    this.username = username;
  }

  getUserLoggedIn() {
    return this.isUserLoggedIn;
  }

  getUserName() {
    return this.username;
  }
}

Can someone help me..........


Solution

  • When you refresh you page the whole application is loaded again that is the component goes through it's life cycle again. Depending upon the architecture of your application you need to save authentication information so it is persisted between page refreshes.

    Most commonly JWT is used when working Angular but it is not always the case. If you are using JWT you should save the JWT token in cookie and when the app reloads check it's presence. If it exits read it from cookie and continue normally otherwise ask user to login again.