简体   繁体   中英

canActivate causing constant refresh - Angular2+

I am attempting to use the canActivate feature on my app routing, however whenever I compile the app the log shows constantly refreshing with fail messages that I had console.log()'d out for visibility.

Is there something I am missing here?

this.router.navigate([''], {queryParams: {returnUrl: state.url}});

will get executed everytime when not logged in, thus causing your infinite redirects as in your router config

{path: '', component: HomepageComponent, canActivate: [AuthGuard]},

Add an explicitly path for an eg LoginComponent. And {path: '**', redirectTo: ''} should also point to some kind of CatchUnmatchedPathComponent where a User gets some kind of 404 page represented.

You are redirecting to the wrong route in your canActivate method. Redirect to login . Here are the change you need to make:

// if not logged in, navigate to login screen
this.router.navigate(['login'], {queryParams: {returnUrl: state.url}});

When you are redirecting to '' , it goes again to the canActivate guard, hence the infinite loop.

在此处输入图片说明

You are navigating to root by this.router.navigate([''], {queryParams: {returnUrl: state.url}}); which causes the guard to kick in again therefore it gets in the loop.

Try this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});

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