角度6的登录页面重定向的身份验证防护?

时间:2019-01-03 10:07:32

标签: angular login

enter image description here

在Angular中,当我在登录页面上登录时,我的登录URL为http://localhost:3000/login,现在我更改为没有登录http://localhost:3000/base/dashboard (this is right url),因此没有登录,它就不会重定向到仪表板页面,而是在登录页面上登录,但是当我输入错误的网址而没有这样的登录名http://localhost:3000/defrtfg却在pageNotFoundComponent(see below screenshot)上重定向时,但我想在登录页面上重定向时却未登录,这是怎么可能的?

Authgaurd.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from './services/user.service';

@Injectable({
  providedIn: 'root'
})
export class AuthguardGuard implements CanActivate{
constructor (private router : Router) {}

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(localStorage.getItem('username')){  
       return true;
    }else{
      this.router.navigate(['/login']);
      return false;
    }
  }
}

app-routing.module.ts

const routes: Routes = [
 { path: '', redirectTo: 'login', pathMatch: 'full' },
 { path: 'login', component : LoginFormComponent },   
 { path : 'base', component : BaseComponent,canActivate : [AuthguardGuard],
 children: [
   { path: '', redirectTo: 'dashboard', pathMatch: 'full' },    
   { path: 'dashboard', component : DashboardComponent },
 ]},
  { path: '**', component : PageNotFoundComponent },   
];

1 个答案:

答案 0 :(得分:3)

尝试一下:

{ path: '**', component : PageNotFoundComponent, canActivate : [AuthguardGuard]}