所以要实现canActivate,你需要制作一个AuthGuard。
什么是 AuthGuard: 它确保用户是否通过身份验证以访问特定 URL。
在这里,我创建了一个示例代码,以便您了解实现警卫的想法。
我创建了一个服务。在其中,有一种方法isAuthenticated 检查令牌,如果令牌可用,则返回真,否则返回假。
我在警卫内部使用了那个服务方法。
在路由中,我设置了我的守卫来处理是否激活该路由。
auth.service.ts
import { Injectable } from '@angular/core';
import { JwtHelper } from '@auth0/angular-jwt';
@Injectable()
export class AuthService {
constructor(public jwtHelper: JwtHelper) {}
// ...
public isAuthenticated(): boolean {
const token = localStorage.getItem('token');
// Check whether the token is expired and return
// true or false
return !!token; (will return either true or false based on the token availability)
}
}
auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
app.routes.ts
import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService as AuthGuard } from './auth/auth-guard.service';
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '' }
];
更多:
https://codecraft.tv/courses/angular/routing/router-guards/
https://ryanchenkie.com/angular-authentication-using-route-guards