0
votes

Hello in the deprecated ng2 routes i have used a protected outlet which navigates to a component only when the user is authenticated.But in new router i am not finding anyone speaking about protected routes.Everyone are using canActivate guard when defining their routes in app.routing.ts file. I feel that rather than defining canActivate guard for route in my route definitions having a protected outlet seems to be an easy way.

@Directive({
selector: 'protected-router-outlet',
})
export class ProtectedOutlet extends RouterOutlet {
private parentRouter: Router;
publicRoutes: any;
constructor(_viewContainer: ViewContainerRef, _loader: DynamicComponentLoader, _parentRouter: Router, @Attribute('name') nameAttr: string, private auth: AuthService) {
    super(_viewContainer, _loader, _parentRouter, nameAttr);

    this.parentRouter = _parentRouter;
    this.publicRoutes = {
        '/Login': true
    };
}
  activate(instruction: ComponentInstruction) {
    var url = this.parentRouter.lastNavigationAttempt;
    var LoggedIn = this.auth.IsLoggedIn();
    if (!LoggedIn) {
        this.parentRouter.navigateByUrl('/Login');
    }
    return super.activate(instruction);
  }
}

Is it possible to have a protected outlet in new Router.If yes how can i use protected outlets because i cant find ComponentInstruction in new routes. can someone please help me out.If i am wrong please suggest me with the correct approach to protect a route.Thank you

1
Why do you want to avoid CanActivate guards? - BeetleJuice
Because i should define for every route which is defined. I am not against CanActivate. But rather than defining canActivate i thought having protected outlet is easy to use.Even if i forget to mention the canActivate the protected outlet handles that so - abhilash reddy

1 Answers

2
votes

If specifying the AuthGuard for every route is too cumbersome, you can do this:

const unprotectedRoutes = [];
const protectedRoutes = [
  // protected routes here
].map((r:Route) => {
  r.canActivate = (r.canActivate) ? [AuthGuard, ...r.canActivate] : [AuthGuard];
  return r;
});

export const routeConfig = [...unprotectedRoutes, ...protectedRoutes];

I'm using this to add a "LogGuard" (which doesn't actually guard anything, but logs navigation) to all of my routes.