【问题标题】:Auth guard not working in angular 5身份验证防护在角度 5 中不起作用
【发布时间】: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


【解决方案1】:

您当前的代码没有问题,如果您对每个组件分别有 routing,请将它们删除并仅将它们放在 app.module.ts p>

【讨论】:

    【解决方案2】:

    如果您使用路由保护,请将其添加到根 app.module 或任何 module.ts 文件中

    providers: [AuthGuard]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 2011-09-02
      • 2017-03-06
      • 2013-06-25
      相关资源
      最近更新 更多