简体   繁体   中英

Is it possible to somehow use negation operator on an Angular route guard?

In my angular 4 app I'm using authGuard to restrict certain pages of an app from being accessible by unregistered users. in these specific routes I use

canActivate: [AuthGuard]

works nicely.

what I couldn't achieve is restrict access of other pages to registered users with that same AuthGuard . so that a registered user won't be able to navigate to sign in / register pages for example.

so logicly i just figured i'd negate that result with ! operator on the AuthGuard

{
    path: 'sign-in',
    component: SignInComponent,
    canActivate: [!AuthGuard]
}

but this approach throws an error

Uncaught (in promise): Error: Token must be defined!

I think creating another route guard just to return the opposite result is a bad practice.

Any way to make this simple approach work?

Thanks!!

No, but you can try

canActivate: [{provide: AuthGuard: useFactory: () => new AuthGuard(false)}]

and use the value passed to the constructor in AuthGuard

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM