在 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; 
}
}
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] }
];

最新更新