Ansar Samad
Ansar Samad

Reputation: 602

how to handle Angular 2 CanActivate Route Guards

I have implemented Route Guards on my application. Before the user access the dashboard route, I have checked whether the user has logged in or not.

It get worked fine user access dashboard after logged in , but if the user try to access the route dashboard without logged in am getting blank page . The CanActivate Guard is executed and it return false.

However, I want to redirect the user to the logging page if the CanActivate is failed.

How can I redirect the user to another Route if the Route Guard failed?

This is i what i have followed

import { Routes, RouterModule } from '@angular/router';
import { AccountPage } from './account-page';
import { LoginRouteGuard } from './login-route-guard';
import { SaveFormsGuard } from './save-forms-guard';
const routes: Routes = [
{ path: 'home', component: HomePage },
{
path: 'accounts',
component: AccountPage,
canActivate: [LoginRouteGuard],
canDeactivate: [SaveFormsGuard]
}
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(routes);

import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { LoginService } from './login-service';
@Injectable()
export class LoginRouteGuard implements CanActivate {
constructor(private loginService: LoginService) {}
canActivate() {
return this.loginService.isLoggedIn();
}
}

Upvotes: 1

Views: 4594

Answers (4)

Anirban Bhadra
Anirban Bhadra

Reputation: 259

1. Create a class which implements CanActivate of router module

    import {Injectable} from '@angular/core';
    import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { LoginService } from './login/login.service';
    // Here LoginService is a custom service to check the user authentication.
    @Injectable()
    export class CanActivateAuthGuard implements CanActivate  {
        constructor(private router: Router, private loginService: LoginService) { };
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
            if (this.loginService.GetAuthStatus()) {
                return true;
            } else {
            this.router.navigate(['/login']);
            return false;
            }
        };
    } 

2. Add the class to provider array to NgModule in the app.module.ts file

       import { CanActivateAuthGuard } from './auth.guard';

     @MgModule({
        providers: [
        ...
        CanActivateAuthGuard,
        ...
        ],
     })

3. In the router constant use the service in the canActivate (provided by angular router) property

    { path: 'dashboard' , component: DashBoardComponent, canActivate: [CanActivateAuthGuard] }

Upvotes: 0

In your Guard you can use Router to redirect to login page:

import { CanActivate, Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { LoginService } from './login-service';
@Injectable()
export class LoginRouteGuard implements CanActivate {
    constructor(private loginService: LoginService, private router: Router) {}
    canActivate() {
        let result = this.loginService.isLoggedIn();
        // Case not logged
        if(!result) {
            this.router.navigate(['/login']);
        }
        return result;
    }
}

Upvotes: 0

mtx
mtx

Reputation: 1682

You can redirect inside the guard by injecting the router into the guard and calling navigate()

import { Router, CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { LoginService } from './login-service';

@Injectable()
export class LoginRouteGuard implements CanActivate {
    constructor(
        private loginService: LoginService,
        private router: Router
    ) {}

    canActivate() {
        if(this.loginService.isLoggedIn()) {
            return true;
        }

        this.router.navigate(['/route/to/wherever/you/want']);
        return false;
}

This is taken from the official docs.

Upvotes: 0

Pengyy
Pengyy

Reputation: 38161

you can inject Router in AuthGuardService and redirect to logging page when this.loginService.isLoggedIn() returned false.

import { CanActivate, Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { LoginService } from './login-service';

@Injectable()
export class LoginRouteGuard implements CanActivate {
  constructor(private loginService: LoginService, private router: Router) {}
  canActivate() {
    if(this.loginService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);    // redirect to login page for example
      return false;
    }
  }
}

Upvotes: 5

Related Questions