Angular2: Prevent authenticated users from accessing specific routes

后端 未结 3 1352
礼貌的吻别
礼貌的吻别 2020-12-31 04:43

I\'ve defined some routes in my main.ts file:

const routes: RouterConfig = [
  { path: \'\', component: HomeComponent },
  { path:          


        
3条回答
  •  旧时难觅i
    2020-12-31 05:23

    I made some researches to see if it's possible to "negate" a guard but seems like you have to make another guard which is the opposite of your guard. Like :

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

    Add it in your bootstrap function as well and you are all set. You just have to do in your routes :

    { path: 'login', component: LoginComponent, canActivate: [PreventLoggedInAccess] },
    

提交回复
热议问题