我目前正在 Angular: 7.2.14 上构建,想看看是否有人可以解释如何使用路由保护、共享服务或其他方式等重定向查询参数。
我试图解决的问题要求查询参数从根 Uri 路径传入,然后将路由重定向到正确的子组件,当路由器更改 Uris 时保持查询完整。
例如,假设您有一个外部 href 链接到一个 angular 应用程序(请参阅下面的路由),并且原始路由 href 是:domain.com?foo=bar
, 因为这是 ''
的根路由然后 angular 会将路由转移到匹配的子路由 ''
这反过来重定向到 'login'
.最终结果将您带到这里 domain.com/#/login
以及我对 ?foo=bar
的查询丢失了。
您如何创建路线、路线防护甚至服务等并保持原始查询同时将您重定向到 domain.com/#/login?foo=bar
的最终位置从根路径开始?
const routes: Routes = [
{
path: '', component: AuthorizeComponent,
children: [
{ path: '', redirectTo: 'login' },
{ path: 'login', component: LoginComponent, canActivate: [LoginGuardService] },
{ path: 'confirm', component: ConfirmComponent, canActivate: [ConfirmGuardService] },
{ path: 'error', component: ErrorComponent },
]
}];
我将尝试在这里展示我的设置。我有一个
LoginGuardService
实现 canActivate
在 canActivate 函数中,我可以使用 router.navigate(['/login'], { queryParams: route.queryParams })
重定向将查询保持在一起,除了这仅在您直接链接到路线时才有效,例如 domain.com/#/login?foo=bar
不是先到根。登录GuardService
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.auth.isLoggedIn()) {
this.router.navigate(['/confirm'], { queryParams: route.queryParams });
} else {
return true;
}
}
ConfirmGuardService
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.auth.isLoggedIn()) {
this.router.navigate(['/login'], { queryParams: route.queryParams });
} else {
return true;
}
}
最佳答案
套装queryParamsHandling: 'preserve'
在您的导航附加功能 ( Resource ) 中:
this.router.navigate(['/confirm'], { queryParamsHandling: 'preserve' });
关于带查询参数的 Angular 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083605/