Angular2: how to “reload” page with router (recheck canActivate)?

蹲街弑〆低调 提交于 2019-12-04 10:58:53

问题


I have routers with canActivate: [ AuthGuard ] and validation inside AuthGuard

How to force check canActivate in same router url ?

For example: Current route is /admin and I have got event like session expired. I have session check in AuthGuard but this check activates only when I execute .navigate(...). How to force run canActivate in same location?

I've tried: this.router.navigate([ this.router.url ]); but angular checks same location and do nothing.

p.s. I can locate to "login page" or other pages when I got session expired event, but I have all redirects inside AuthGuard and I do not want to repeat the same redirects in all other events, I need just like location.reload() but in Angular2 routes.

Main question sounds like: How to force rerun canActivate guards in current location?


回答1:


My temporary solution:

auth.service.ts

import { Injectable, Injector } from '@angular/core';
import { ActivatedRoute, Router, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthService {

  constructor(private route: ActivatedRoute,
              private router: Router,
              private injector: Injector) {
    this.forceRunAuthGuard();
  }

  // Dirty hack for angular2 routing recheck
  private forceRunAuthGuard() {
    if (this.route.root.children.length) {
      // gets current route
      const curr_route = this.route.root.children[ '0' ];
      // gets first guard class
      const AuthGuard = curr_route.snapshot.routeConfig.canActivate[ '0' ];
      // injects guard
      const authGuard = this.injector.get(AuthGuard);
      // makes custom RouterStateSnapshot object
      const routerStateSnapshot: RouterStateSnapshot = Object.assign({}, curr_route.snapshot, { url: this.router.url });
      // runs canActivate
      authGuard.canActivate(curr_route.snapshot, routerStateSnapshot);
    }
  }

}

app.routes.ts

  { path: 'faq', canActivate: [ AuthGuard ], component: FaqComponent },
  { path: 'about', canActivate: [ AuthGuard ], component: AboutUsComponent },
  { path: 'upgrade', canActivate: [ AuthGuard ], component: UpgradeComponent },

This code runs AuthGuard again.



来源:https://stackoverflow.com/questions/45680250/angular2-how-to-reload-page-with-router-recheck-canactivate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!