angular - 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 守卫因此不适用。
我正在考虑创建一个额外的组件来处理重定向,但它似乎也有点
解决方案
我想出了如何解决这个问题。
您可以在通配符路由上添加 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/
推荐阅读
- windows - remove-netnatstaticmapping :不支持请求的操作。尝试删除 windows docker 容器端口映射时
- asp.net - ASP.NET 中的后台线程 - 什么机制最好?
- django - “第 14 行的块标签无效:'empty',预期为 'endblock'。您是否忘记注册或加载此标签?”
- c++ - 从引用创建一个指向基类的智能指针
- bash - 基于通过 grep 管道传输的环境 $PATH 的返回构造一个 If 语句(使用 bash)
- xslt-1.0 - 使用 XSLT 合并
- java - 如何使用 ASM 读取 Java 类方法注解值
- java - 将 JHipster 项目部署到 Kubernetes 时出现“FileNotFoundException: /var/lib/h2/data/odp.mv.db (Permission denied)”
- vue.js - 如何使用 Vue js 将 div 替换为 html onclick?
- python - 冻结队列和线程