6

Here is my static login service

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;
}
}

My authguard service

  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;
    }
}

my 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]
})

I just tested this by entering a route directly in browser url for example /home which has canactivate enabled in its route config but when i do so the home contents are displayed instead of redirecting to the login page.Need too know what's wrong here any help will be really appreciated thanks in advance :)

4

2 回答 2

5

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

于 2017-12-09T08:03:11.333 回答
1

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

providers: [AuthGuard]
于 2020-11-14T13:44:58.733 回答