路由时如何做一些动作?

时间:2019-10-25 13:08:59

标签: angular angular2-routing

当令牌过期时,我尝试注销用户。我用jwt。我尝试在app.component中执行此操作,但是直到刷新页面后它才有效。路由时是否有系统地检查它的方法?数据存储在localStorage中。

2 个答案:

答案 0 :(得分:0)

您可以在激活路由之前调用路由保护器进行检查。您需要在每种路由配置的canActivate帮助下在路由模块中进行配置。 在警卫中实施canActivate以检查令牌是否已过期。如果是这样,您可能想重定向到登录页面。

引用https://angular.io/guide/router#canactivate-requiring-authentication

答案 1 :(得分:0)

您可以如下创建AuthGuard:

import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import "rxjs/add/operator/toPromise";
import { AuthService } from "./auth.service";
import { User } from "models/user.model";

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const isLoggedIn = this.authService.isLoggedIn;
    const currentUser: User = this.authService.currentUser;

    if (isLoggedIn == true && currentUser != null) {
      // check if route is restricted by role
      const roles = route.data.roles;
      if (roles) {
        const userRolesValid: boolean = this.authService.validateUserRoles(roles);
        if (userRolesValid == false) {
          // role not authorised so redirect to home page
          this.router.navigate(["/"]);
          return false;
        }
      }

      return true;
    }

    // not logged in so redirect to login page with the return url
    this.authService.logout();
    this.router.navigate(["/login"], { queryParams: { returnUrl: state.url } });
    return false;
  }
}

然后,您必须将AuthGuard as canActivate属性添加到您要对其进行检查的所有应用程序路由中:

  { path: "home", component: HomeComponent, canActivate: [AuthGuard]}

请不要忘记也将AuthGuard作为提供程序导入到app.modules文件中

import { AuthGuard } from "services/auth.guard";

@NgModule({
    providers: [ AuthGuard ]

})