我有一个网站,它分为用户可以访问的普通页面和只能由管理员访问的另一个页面(即ngx-admin)。
因此,为了阻止用户访问管理仪表板,我设置了一个身份验证保护,它将用户重定向到登录页面,如果他们有错误的凭据,它会将他们重定向到网站的主页,但出于某种原因,无论何时我尝试访问主页或其他任何我总是被重定向登录页面的东西。
这是我的应用程序路由模块:
import { ExtraOptions, RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import {
NbAuthComponent,
NbLoginComponent,
NbLogoutComponent,
NbRegisterComponent,
NbRequestPasswordComponent,
NbResetPasswordComponent,
} from '@nebular/auth';
import { AuthGuard } from './auth-guard.service';
import { HomeComponent } from './Home/home.component';
import { OffreAComponent } from './offrea/offrea.component';
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'offreappel', component: OffreAComponent},
{ path: 'users', loadChildren: 'app/pages/pages.module#PagesModule', canActivate: [AuthGuard]},
{
path: 'auth',
component: NbAuthComponent,
children: [
{
path: '',
component: NbLoginComponent,
},
{
path: 'login',
component: NbLoginComponent,
},
{
path: 'register',
component: NbRegisterComponent,
},
{
path: 'logout',
component: NbLogoutComponent,
},
{
path: 'request-password',
component: NbRequestPasswordComponent,
},
{
path: 'reset-password',
component: NbResetPasswordComponent,
},
],
},
{ path: '**', pathMatch: 'full', redirectTo: 'users'},
];
const config: ExtraOptions = {
useHash: true,
};
@NgModule({
imports: [RouterModule.forRoot(routes, config)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
这是我的 AuthGuard 服务:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { NbAuthService } from '@nebular/auth';
import { tap } from 'rxjs/operators';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: NbAuthService, private router: Router) {}
canActivate() {
return this.authService.isAuthenticated().pipe(
tap(authenticated => {
if (!authenticated) {
this.router.navigate(['auth/login']);
}
}),
);
}}