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"
}
];
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.