这是我的静态登录服务
login(email: string, password: string) {
debugger;
const user = {
username: email,
password: password,
};
if (email === "admin" && password === "admin") {
localStorage.setItem("currentUser", JSON.stringify(user));
}
if (localStorage.getItem("currentUser")) {
// logged in so return true
return user;
} else {
return false;
}
}
我的身份验证服务
export class AuthGuard implements CanActivate {
constructor(private router: Router) {
}
isAuthenticated(): boolean{
if (localStorage.getItem("currentUser")) {
return true;
}
else{
return false;
}
}
canActivate(): boolean {
if (!this.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
我的 app.routing.ts
const appRoutes: Routes = [
{ path: "home", component: HomeComponent ,canActivate: [AuthGuard]},
{ path: "login", component: AuthComponent },
{ path: "", component: AuthComponent },
{ path: "employees", component: EmpComponent,canActivate: [AuthGuard] },
// otherwise redirect to home
{ path: "**", redirectTo: "/" }
];
app.module.ts
@NgModule({
declarations: [AppComponent, HeaderComponent, FooterComponent],
imports: [
BrowserModule,
FormsModule,
SharedModule,
HomeModule,
AuthModule,
EmpModule,
routing,
Ng4LoadingSpinnerModule,
AlertModule.forRoot()
],
providers: [AuthGuard, AuthenticationService],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
bootstrap: [AppComponent]
})
我只是通过直接在浏览器 url 中输入路由来测试这一点,例如/home 在其路由配置中启用了 canactivate 但是当我这样做时,主页内容会显示而不是重定向到登录页面。需要知道这里有什么问题有什么帮助将非常感谢提前:)
最佳答案
如果您有 ,您当前的代码没有问题routing
分别为每个组件删除它们并仅将它们放在 中app.module.ts
关于angular - Auth 守卫在 Angular 5 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47726206/