Angular2: Prevent authenticated users from accessing specific routes

允我心安 提交于 2019-11-30 08:38:41

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] },

Make ts file name auth.guard.ts put following code on that

Write guard code

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

Add bellow code in your routing ts file

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 }
                ]  
  },

Add providers in your app.module.ts file

app.module.ts

@NgModule({
  declarations: [
    AppComponent
    --------
  ],
  imports: [
    BrowserModule
    --------
  ],
  providers: [      
    AuthGuard        
  ],
  bootstrap: [AppComponent]
})

You could write a guard like this:

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

import { AuthService } from './your-auth.service';

@Injectable()
export class UserAccessGuard implements CanActivate {
    constructor(private authService: AuthService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return route.data['onlyGuests'] != authService.isAuthenticated();
    }
}

And then use it in your route definition:

const routes: Routes = [
  { path: '', redirectTo: 'home' },

  // accessible only to guests
  {
      path: '',
      component: HomeComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },
  {
      path: 'login',
      component: LoginComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },

  // accessible only to authenticated users
  {
      path: 'dashboard',
      component: DashboardComponent,
      canActivate: [ UserAccessGuard ]
  }
];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!