简体   繁体   中英

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

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

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM