【发布时间】:2018-05-23 09:34:18
【问题描述】:
这是我的静态登录服务
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;
}
}
我的 authguard 服务
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,但是当我这样做时,显示主页内容而不是重定向到登录页面。需要也知道出了什么问题在这里任何帮助都将非常感谢提前感谢:)
【问题讨论】:
-
我认为问题是本地存储总是有值,清除它并测试
-
@Sajeetharan 我没有登录,只是在浏览器 url 中输入了启用 canactivate 的路由。所以 localstorage 中没有值。
-
奇怪,我可以看看你的完整代码
-
这里已经有了!
-
我的意思是调试
标签: angular authentication angular-router-guards