Angular2:防止经过身份验证的用户访问特定路由

Emu*_*Emu 14 angular2-routing angular

routes在我的main.ts文件中定义了一些:

const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: '', redirectTo: 'home', terminal: true },
  { path: 'dashboard', component: DashboardComponent, canActivate: [LoggedInGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'about', component: AboutComponent } 
];
Run Code Online (Sandbox Code Playgroud)

成功登录后,我希望我的经过身份验证的用户可以使用特定路由(例如dashboard).没有登录他们无法访问,dashboard但他们可以访问about,home,login

我设法限制用户遍历dashboard无登录,使用CanActivate.

canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true; 
    }
    this.router.navigateByUrl('/login');
    return false;
  }
Run Code Online (Sandbox Code Playgroud)

但是CanActivate在成功登录后使用这些路线和方法,用户也可以转到像login,等路线home.我怎么能防止这种情况?

NB我正在使用angular2 RC4.

Ada*_*m S 17

我做了一些研究,看看是否有可能"否定"一名后卫,但看起来你必须做出另一个与后卫相反的后卫.喜欢 :

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthService } from './your-auth.service';

@Injectable()
export class PreventLoggedInAccess implements CanActivate {

  constructor(private authService: AuthService) {}

  canActivate() {
    return !this.authService.isLoggedIn();
  }
} 
Run Code Online (Sandbox Code Playgroud)

将它添加到您的引导功能中,您就完成了所有设置.你只需要做你的路线:

{ path: 'login', component: LoginComponent, canActivate: [PreventLoggedInAccess] },
Run Code Online (Sandbox Code Playgroud)

  • 我希望你可以像这样`canActivate:[!LoggedInGuard]`来否定它. (2认同)

小智 5

使 ts 文件名 auth.guard.ts 在其上放置以下代码

写守卫代码

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router) { }
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }
        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

在路由 ts 文件中添加波纹管代码

app-routing.module.ts

{
      path: 'user', component: UserComponent,canActivate: [AuthGuard] ,
      children: [{ path: 'home', component: HomeComponent },
                 { path: 'view/:id', component: UserViewComponent },
                 { path: 'add', component: UserAddComponent },
                 { path: 'edit/:id', component: UserAddComponent }
                ]  
  },
Run Code Online (Sandbox Code Playgroud)

在 app.module.ts 文件中添加提供程序

app.module.ts

@NgModule({
  declarations: [
    AppComponent
    --------
  ],
  imports: [
    BrowserModule
    --------
  ],
  providers: [      
    AuthGuard        
  ],
  bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)