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

后端 未结 1 1647
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 02:13

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

How to force check canActivate in same router url ?

1条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 02:30

    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.

    0 讨论(0)
提交回复
热议问题