例如,在app-routing.module.ts中定义路由:
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
...
];
例如,在auth.guard.ts中定义AuthGuard:
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean {
return this.authService.isLoggedIn()
.pipe(
map((isLoggedIn: boolean) => {
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
})
);
}
}
例如,在auth.service.ts中定义AuthService:
@Injectable({
providedIn: 'root'
})
export class AuthService {
// use BehaviorSubject to keep track of login state
private loggedIn = new BehaviorSubject(false);
constructor() { }
isLoggedIn(): Observable {
// return BehaviorSubject as an Observable
return this.loggedIn.asObservable();
}
login() {
this.loggedIn.next(true);
}
logout() {
this.loggedIn.next(false);
}
}
在login.component.ts中处理用户登录:
export class LoginComponent implements OnInit {
constructor(private authService: AuthService) {}
ngOnInit() {}
login() {
// authenticate user and set isLoggedIn to true
this.authService.login();
}
}
在navbar.component.ts中处理用户注销:
export class NavbarComponent implements OnInit {
constructor(private authService: AuthService) {}
ngOnInit() {}
logout() {
// log out user and set isLoggedIn to false
this.authService.logout();
}
}