朋友们,我被queryParamsHandling参数困住了,这个参数不像预期的那样工作。在我的应用程序中,我有一个重定向服务,它简单地使用选择器检查用户角色,并根据角色重定向到特定urls。密码在下面。我想要的只是保存queryParams并将它们重定向在不同的路径上。我发现queryParamsHandling就是为了这个。但是它总是刷新重定向URL上的所有queryParams。我要初始url,如:,重定向后是,仍然持有查询param1。不管有多少queryParams -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)
)
}
}
我甚至调试了这段代码,并且可以清楚地看到queryparamshandling何时被检查。在那一刻,currentUrlTree总是空。
case 'preserve':
q = this.currentUrlTree.queryParams;
break;
如何保存queryParams并将其传递给重定向URL?谢谢
更新:在组件中(当app加载时), queryparamshandling按预期工作。问题是,我试图在canActivate处理中使用它。在这种情况下如何通过queryParams?
发布于 2020-12-08 20:53:09
queryParamsHandling在canActivate警卫期间不工作。如果要保留queryParams,则需要使用ActivatedRouteSnapshot手动传递queryParams
https://stackoverflow.com/a/45843291/372212
解决方案正在起作用。它也有一个解释。
发布于 2020-12-08 20:40:47
好像你有个错误:
试着改变
this.router.navigate([ '/main-unauth', { queryparamshandling: 'preserve' } ])
至
this.router.navigate([ '/main-unauth' ], { queryparamshandling: 'preserve' } )
https://stackoverflow.com/questions/65206073
复制相似问题