В Angular, если вход в систему выполнен, пользователю не следует снова заходить на страницу входа в систему, пока он не выйдет из системы. Как реализовать это в Angular
После входа в систему, пока пользователь не выйдет из системы, маршрут страницы входа не должен быть доступен. как это реализовать в Angular. Пожалуйста, дайте подробное объяснение с необходимым кодом.
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs/Observable';
import {AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
@Injectable()
export class AuthRedirectService {
//service which helps to redirect to profile page from login/sigup page if an user is already logged in.
constructor(private auth: AuthService, private router: Router,
private angularfireauth: AngularFireAuth) { }
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> |
Promise<boolean> | boolean {
//this.router.navigate(['/profile']);
if (this.auth.isUserLoggedIn()==false) {
console.log("login status from guard: ",this.auth.isUserLoggedIn);
return true;
}
return false;
}
}
2 ответа
Include the following code in authguard.ts:
import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class AuthGuard {
[x: string]: any;
constructor(private router: Router) {
}
canActivate(routeerstate?: any) {
if (!this.auth.isUserLoggedIn()) {
this.router.navigate(['login']); // not authenticated so always redirect to login
} else if(routeerstate._routerState.url === '/login'){
this.router.navigate(this.router.url]); // authenticated so stay in the current url
}
}
}
routeerstate._routerState.url gets you unactivated URL(to URL) i.e the url the user is trying to enter, this.router.url gets you the current URL (from URL), rest you can get it from comments in above code
export const routes: Routes = [
{ path: 'login', component: LoginComponent, pathMatch: 'full',canActivate: [AuthGuard] },
{ path: 'authenticatedpage1', component: authenticatedPageComponent, pathMatch: 'full',canActivate: [AuthGuard] }
];