0

I'm new to angular 2 actually im facing issue when i am refresh its redirect to login page but actually i wants redirected to dashboard

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    // get observable
    const observable = this.store.select(isAuthenticated);
        // redirect to sign in page if user is not authenticated
    observable.subscribe(authenticated => {
      if (!authenticated) {
        this.router.navigate(['/login']);
      }
    });

    return observable;

  }

routing module:

const routes: Routes = [
  {
    canActivate: [AuthGuard],
    path: "dashboard",
    loadChildren: "./dashboard/dashboard.module#DashboardModule"
  },
  {
    path: "",
    pathMatch: "full",
    redirectTo: "dashboard"
  }
];
krezus
  • 1,281
  • 1
  • 13
  • 29
dhinesh
  • 1
  • 4

1 Answers1

0

Please elaborate your question. Not able to identify your problem correctly, but as per my understanding you can write guard as

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isLoggedIn
  .take(1)
  .map((isLoggedIn: boolean) => {
    console.log(isLoggedIn)
    if (!isLoggedIn) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  });
}

and in auth.seervice.ts

 private loggedIn = new BehaviorSubject<boolean>(this.loggedInUser());
 get isLoggedIn() {
     if (localStorage.getItem('userDetails'))
        this.loggedIn.next(true);
     return this.loggedIn.asObservable();
  }
loggedInUser(): boolean {
   return JSON.parse(localStorage.getItem('loggedInUser'));
}

Now when you refresh the browser, guard will check for logged in user data.

If you want to redirect user to dashboard everytime when user refresh the browser,then you can write

if (!isLoggedIn) {
  this.router.navigate(['login']);
  return false;
}else{
   this.router.navigate(['dashboard']);
   return true;
}

you can refer this articles for detail explanation angular-authentication-using-route-guards and router-guards

Sufiyan Momin
  • 121
  • 1
  • 10