angular - Auth 守卫在 Angular 5 中不起作用

标签 angular authentication 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;
}
}

我的身份验证服务
  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/

相关文章:

angular - 类型 'pipe' Angular 6 上不存在属性 'void'

angular - 将 mat-radio-group 绑定(bind)到可空 bool 值的正确方法?

angular - 使用 RXJS 和 Angular 进行简单的表过滤

authentication - 如何处理 JSF 中的动态角色或用户名更改?

authentication - Spring Data REST 中的 CORS 预检请求

html - 使用 scrapy 获取 crawlspider 来处理经过身份验证(登录)的用户 session

angular - rxjs switchMap 在 Angular Guard 中不起作用?

angular - 在 canActivate Guard 中访问 ActivatedRoute 的组件

php - Laravel Sanctum 身份验证 :sanctum middleware with Angular SPA unauthenticated response

Angular 4 Multiple Guards - 执行顺序