我正在使用 auth0 中的 angular2-jwt 包。一切工作正常,但现在我想知道如何重定向当前位于某个路径上的用户,该路径由我的身份验证守卫在其他地方保护。现在,当用户尝试访问受保护的路径时,它会进行重定向。
我知道我可以隐藏组件中的对象,但是我必须在每个受保护的组件中执行此操作,这还不清楚。
这是我的路线:
const appRoutes: Routes = [
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
{path: '', component: HomeComponent},
{path: 'user/edit', component: EditProfileComponent, canActivate: [AuthGuard]},
];
Run Code Online (Sandbox Code Playgroud)
这是我的警卫服务:
...
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {
}
canActivate() {
if (this.auth.loggedIn()) {
return true;
}
this.router.navigate(['/']);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)