Routerstatesnapshot State.url在登录后重新连接到以前的url时会附加初始路由



我正在尝试实现一个功能,如果用户试图在不登录的情况下访问URL,那么我将使用AUTH GUARD将用户重定向到带有returnURL的登录页面,然后在成功登录后将用户重定向至该特定URL(遵循本教程-https://jasonwatmore.com/post/2016/12/08/angular-2-redirect-to-previous-url-after-login-with-auth-guard)。但它总是将我的初始路由附加到returnUrl,例如,如果我试图访问localhost:4200/job/111,那么它会重定向到localhost:4200/auth/login?returnUrl=%2Dashboard%2Fjob%2F111,因此我的重定向失败。以下是我的路线:

export const AppRoutes: Routes = [
{ path: 'auth', canActivate: [HashGuard], loadChildren: './modules/auth/auth.module#AuthModule' },
{
path: '',
canActivate: [ AuthGuard],
loadChildren: './modules/dashboard-v3/dashboard-v3.module#DashboardV3Module'
},
{
path: 'mobile',
canActivate: [AuthGuard],
loadChildren: './modules/mobile/mobile.module#MobileModule'
},
{
path: '**',
pathMatch: 'full',
redirectTo: 'error'
},
{
path: 'error',
canActivate: [HashGuard],
loadChildren: './modules/error/error.module#ErrorModule'
},
];

我的身份验证保护代码是这样的,

export class AuthGuard implements CanActivate {
constructor(
private storage: StorageService,
private router: Router,
){ }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log('auth guard called');
if(this.storage.retrieveAccessToken() && this.storage.retrieveAuthToken()){
return true;
} else if(!state.url.match('auth') && !state.url.match('join')) {
console.log('RouterStateSnapshot values', state);
return this.router.navigate(['/auth/login'], {queryParams: {returnUrl: state.url}});
} else {
return true;
}
}
}

任何帮助都将不胜感激,提前感谢!

在您的示例中,您想要访问像job/111这样的路由,因此在您的防护中,您处于第二个条件!state.url.match('auth') && !state.url.match('join'),因此您导航到auth/login路由。

我认为问题出在你的防守上,你应该这样做:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log('auth guard called');
if (this.storage.retrieveAccessToken() && this.storage.retrieveAuthToken()) {
return true;
} else {
console.log('RouterStateSnapshot values', state);
this.router.navigate(['/auth/login'], {queryParams: {returnUrl: state.url}});
return false;
}

然后,如果经过身份验证,您可以使用returnUrl作为导航路径。

重定向的原因是在绕过身份验证登录之后。您必须在/dashboard内进行另一次重定向。

this.router.navigateByUrl(this.returnUrl);

应更改为:

this.router.navigateByUrl(this.returnUrl,  { skipLocationChange: true });

最新更新