【发布时间】:2019-05-10 19:13:56
【问题描述】:
我目前正在构建 Angular: 7.2.14 并想看看是否有人可以解释如何使用路由保护、共享服务或其他方式等来重定向查询参数。
我要解决的问题需要查询参数从根 Uri 路径进入,然后将路由重定向到正确的子组件,从而在路由器更改 Uri 时保持查询不变。
例如,假设您有一个外部 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 },
]
}];
我会尝试在这里展示我的设置。我确实有一个实现canActivate 的LoginGuardService 并且在canActivate 函数中我可以使用router.navigate(['/login'], { queryParams: route.queryParams }) 重定向保持查询在一起,除非这仅在您直接链接到domain.com/#/login?foo=bar 之类的路由时才有效,而不是先链接到根目录.
LoginGuardService
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;
}
}
【问题讨论】:
标签: angular routing angular-ui-router angular2-routing url-routing