Angular2: how to "reload" a page using a router (double-check canActivate)?

I have routers with canActivate: [ AuthGuard ]and checking insideAuthGuard

How to force check canActivatein same router url?

For example: The current route /admin, and I got an event like session expired. I have a session check AuthGuard, but this check is only activated upon execution .navigate(...). How to force start canActivatein the same place?

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

ps I can find the “login page” or other pages when I got it session expired event, but I have all the redirects inside AuthGuardand I don’t want to repeat the same redirects in all other events, I just need to like location.reload(), but in the Angular2 routes.

The main question is : How to get reerun canActivateguards at your current location?

+6
source share
1 answer

My workaround:

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 again AuthGuard.

+2
source

All Articles