这是我的静态登录服务
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]
})
我刚刚在浏览器网址中输入了一个路由,例如/ home,它在路由配置中启用了canactivate,但是当我这样做时,会显示主页内容而不是重定向到登录页面。需要知道什么&# 39;在这里错了任何帮助将非常感谢提前感谢:)
答案 0 :(得分:3)
您当前的代码没有问题,如果您对每个组件分别 routing
,请将其删除并仅在 app.module.ts
强>
答案 1 :(得分:1)
如果您使用路由防护,请将其添加到root app.module或任何module.ts文件中
providers: [AuthGuard]