【发布时间】:2021-03-20 04:43:00
【问题描述】:
朋友们,我遇到了无法按预期工作的 queryParamsHandling 参数。 在我的应用程序中,我有一个 redirect 服务,它只是通过使用选择器并根据角色重定向到特定的 url 检查用户角色。代码如下。我想要的只是保存 queryParams 并将它们重定向到不同的路线上。我发现 queryParamsHandling 就是为了这个。但它总是刷新重定向 URL 上的所有 queryParams。 我希望初始网址如:http://main-page.com?param1=500 重定向为 http://main-page-unauth.com?param1=500 后仍保留查询参数 1。无论有多少查询参数,这都适用 - 1,2,3...1000
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { select, Store } from "@ngrx/store";
import * as fromAuth from "../reducers";
import { map, take, tap } from "rxjs/operators";
import { HttpParams } from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class RedirectGuardService implements CanActivate {
constructor(
private router: Router,
private store: Store<fromAuth.State>,
private activatedRoute: ActivatedRoute
) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.store.pipe(
select(fromAuth.selectRole),
tap((role) => {
if (role)
this.router.navigate([state.url + '-' + role]).then()
else
this.router.navigate([ '/main-unauth'], { queryparamshandling: 'preserve' })
.then()
}),
take(1),
map(() => true)
)
}
}
我什至调试了那段代码,并且可以清楚地看到查询参数处理何时被检查。在那一刻 currentUrlTree 总是 null。
case 'preserve':
q = this.currentUrlTree.queryParams;
break;
如何保存 queryParams 并将其传递给重定向的 URL?谢谢
更新: queryparamshandling 在组件中按预期工作(加载应用程序时)。问题是我试图在 canActivate 处理中使用它。在这种情况下如何传递 queryParams ?
【问题讨论】:
-
在同一行代码中,我可以通过 windows.location.search{href} 访问 queryParams