即使我试图访问另一个页面,Angular仍将我重定向到登录页面

时间:2019-05-14 14:06:59

标签: html angular ngx-admin

我有一个网站,该网站分为用户可以访问的常规页面和只能由管理员访问的页面(即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']);
        }
    }),
);
}}

1 个答案:

答案 0 :(得分:0)

由于路由错误,您有一个重定向users

   { path: '**', pathMatch: 'full', redirectTo: 'users'},

因此,每次您转到错误的路径时,它都会重定向到:

{ path: 'users', loadChildren: 'app/pages/pages.module#PagesModule', canActivate: [AuthGuard]}

我会考虑添加一个页面,该页面的默认路径是路由,当路由不匹配时,重定向到该页面:

{ path: '', component: HomeComponent},
{ path: '**', pathMatch: 'full', redirectTo: ''},

要注意的另一件事是检查您是否确实需要useHash。这仅在某些环境中是必需的。