Mel*_*vin 6 authentication angular angular-router-guards
这是我的静态登录服务
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的身份验证服务
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的 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: "/" }
];
Run Code Online (Sandbox Code Playgroud)
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]
})
Run Code Online (Sandbox Code Playgroud)
我只是通过直接在浏览器 url 中输入路由来测试这一点,例如 /home 在其路由配置中启用了 canactivate 但是当我这样做时,主页内容会显示而不是重定向到登录页面。需要知道这里有什么问题有什么帮助将非常感谢提前:)
| 归档时间: |
|
| 查看次数: |
8784 次 |
| 最近记录: |