0

我在 app.module.ts 中有以下路由配置,

{
    path: 'login',
    component: loginComponent,
    canActivate: [loggerService]
}, {
    path: '',
    component: AppComponent,
    canActivate: [loggerService]
}, {
    path: '/home',
    redirectTo: ''
}, {
    path: '/blog',
    component: BlogComponent,
    canActivate: [loggerService]
}

当调用任何路由时,我想要一个方法来运行。例如,记录访问或预先请求某些数据。是否有任何默认的用户定义或内置方法可用于实现此目的?

4

1 回答 1

1

是的。有一种方法可以实现 Auth 保护。下面是例如:

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

    @Injectable()
    export class AuthGuard implements CanActivate, CanActivateChild {

      constructor(private router: Router) {
      }

      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (condition)) {
          return true;
        }
        this.router.navigate(['/unauthorized']);
        return false;
      }

      canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
      }
    }

在您的路线中:

import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from 'Your Location/auth-guard.service';

const ROUTES: Routes = [
  {
    path: '',
    canActivateChild: [AuthGuard],
    children: [
      {path: '', component: CardbrandComponent}     
      ]

  }
];
于 2017-05-02T11:18:07.703 回答