首页 > 解决方案 > Angular 2+ 条件通配符重定向

问题描述

我有不同的路线,每条路线都代表向导中的一个步骤。

const routes: Routes = [
  {
    path: ':id',
    component: ParentComponent,
    children: [
      {path: 'step1', component: Step1Component},
      {path: 'step2', component: Step2Component},
      {path: 'step3', component: Step3Component},
      {path: 'step4', component: Step4Component},
      {path: '**', redirectTo: '???'}
    ]
  }
];

现在我想要一个条件redirectTo,当用户在第 3 步并访问根 url 时,他将被重定向到第 3 步。

我想在重定向上执行的逻辑示例:

if(this.stepService.getCurrentStep(id) === 3) {
  return 'step3';
} else {
  return 'step1';
}

但是,所有路线仍然应该可以访问,这样当用户转到 rout /step2 或 /step4 时,他不会被重定向到第 3 步。我认为 canActivate 守卫因此不适用。

我正在考虑创建一个额外的组件来处理重定向,但它似乎也有点

标签: angular

解决方案


我想出了如何解决这个问题。

您可以在通配符路由上添加 canActivate 保护:

const routes: Routes = [
  {
    path: ':id',
    component: ParentComponent,
    children: [
      {path: 'step1', component: Step1Component},
      ...
      {path: '**', canActivate:[RedirectGuard]}
    ]
  }
];

然后在守卫中你应该返回一个 UrlTree 而不是布尔值:

@Injectable({
  providedIn: 'root'
})
export class RedirectGuard implements CanActivate {

  constructor(private stepService: StepService) {}

   canActivate(
     next: ActivatedRouteSnapshot,
     state: RouterStateSnapshot): Observable<UrlTree> {
     const id = next.parent.params.id;
     // Some logic  
     return of(this.router.parseUrl(state.url + '/rejection'));
  }
}

请注意,此解决方案需要 Angular 7.1+

学分转到这篇博文:https ://juristr.com/blog/2018/11/better-route-guard-redirects/


推荐阅读