Angular CanActivate 守卫 - createUrlTree 相对导航

Lpp*_*Edd 5 angular-routing angular

我目前有一个路线守卫,例如

export class EntityGuard implements CanActivate {
  constructor(private readonly router: Router, ...) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> {

  ...
Run Code Online (Sandbox Code Playgroud)

为 URL 激活此防护

basePath/select/10/123
Run Code Online (Sandbox Code Playgroud)

意思是

basePath/select/:type/:id
Run Code Online (Sandbox Code Playgroud)

当满足某个条件时,我需要强制导航回到

basePath/select/:type
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点createUrlTree?例如

if (...) {
   return of(this.router.createUrlTree([../', type]));
}
Run Code Online (Sandbox Code Playgroud)

我需要设置

{ relativeTo: parent }
Run Code Online (Sandbox Code Playgroud)

选项。但是我似乎无法找到一种方法来做到这一点。


我目前的解决方案是

private navigateBack(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  const end = state.url.indexOf(route.url[route.url.length - 1].path);
  const parentUrl = state.url.slice(0, end);
  return of(this.router.createUrlTree([parentUrl]));
}
Run Code Online (Sandbox Code Playgroud)

我真的不喜欢。字符串操作对我来说是个大问题。

小智 7

我感觉在同样的情况下,并得到了类似的解决方案。主要问题是如果我们ActivateRoute使用构造函数注入,我们会得到之前的路由。他们刨通过ActivateRoutecanActivate方法代替ActivatedRouteSnapshot

这是票:https : //github.com/angular/angular/issues/22763

您可以保留您的解决方案,直到有角度的团队创建更好的解决方案。

问候。