如何处理Angular 2 CanActivate Route Guards

时间:2017-05-21 16:32:54

标签: angular angular2-routing angular2-services

我在我的应用程序上实现了Route Guards。在用户访问仪表板路由之前,我已检查用户是否已登录。

登录后,它可以获得良好的用户访问仪表板,但如果用户尝试访问路由仪表板而未登录,则会获得空白页面。执行CanActivate Guard并返回false。

但是,如果CanActivate失败,我想将用户重定向到日志页面。

如果Route Guard失败,如何将用户重定向到另一条路线?

这就是我所遵循的



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




4 个答案:

答案 0 :(得分:4)

您可以在Router中注入AuthGuardService,并在logging返回false时重定向到this.loginService.isLoggedIn()页面。

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

答案 1 :(得分:0)

您可以通过将路由器注入警卫并调用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;
}

这取自official docs

答案 2 :(得分:0)

在Guard中,您可以使用Router重定向到登录页面:

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

答案 3 :(得分:0)

1。创建一个实现路由器模块的CanActivate的类

    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。将类提供者添加到app.module.ts文件中的NgModule

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

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

3。在路由器常量中使用canActivate中的服务(由角度路由器提供)属性

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