angular - 如何根据解析的路由数据路由到子路由?
问题描述
我正在加载一个带有来自解析器的数据的模块。加载的模块具有通常的空路径重定向到第一个子路由。但是我想根据解析的数据重定向到特定的路由。
在当前示例中,我有一个包含三个组件的子模块。根模块中的解析器提供组件应重定向到的数据。
应用模块:
const routes = [
{
path: '',
redirectTo: 'steps',
pathMatch: 'full'
}, {
path: 'steps',
loadChildren: './steps/steps.module#StepsModule',
resolve: {
step: StepResolver,
}
},
]
@NgModule({
imports: [ BrowserModule, RouterModule.forRoot(routes) ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
子模块:
const routes = [
{
path: '',
redirectTo: 'step1', // <-- this has to be dynamic based on the provided data
pathMatch: 'full'
}, {
path: 'step1',
component: Step1Component
}, {
path: 'step2',
component: Step2Component
}, {
path: 'step3',
component: Step3Component
},
]
@NgModule({
imports: [ CommonModule, RouterModule.forChild(routes) ],
declarations: [ Step1Component, Step2Component, Step3Component ],
})
export class StepsModule { }
解析器返回应重定向到的步骤
@Injectable({
providedIn: 'root'
})
export class StepResolver implements Resolve<string> {
resolve(route: ActivatedRouteSnapshot): Observable<string> {
return of('step2');
}
}
如何根据提供的数据重定向到路由?我可以使用任何路由挂钩吗?
通过:
- 空子路径上的 CanActivate -> 在提供后调用 CanActivate,因此:没有数据
- 在空子路径中加载一个空组件并在 OnInit 触发重定向->对我来说有点臭
解决方案
您可以评估下一步需要做什么,然后导航到特定路线:
this.route.navigate([yourStep]);
您必须导入Router
:
constructor(private route: Router) { }
编辑:
创建一个类似这样的服务:
goToStep(step: string) {
this.route.navigate([step]);
}
考虑到您提供的代码的解析器:
resolve(route: ActivatedRouteSnapshot): Observable<string> {
return this.stepService.goToStep('step2');
}
推荐阅读
- apache - Apache AliasMatch 和 ZF 样式的重写导致内部重定向回文档根目录
- r - 无法使用 imputeMCA 获取完整的数据集
- python - 如何使用 Pyinstaller 修复“OSError:无法打开配置文件”
- flutter - 如何在 Dart 中打开枚举?
- javascript - 具有 onChange 功能的 React 组件,需要使用扩展运算符对其进行转换以包含更多属性
- android - 适用于 Android 的 React-Native:无法连接到开发服务器
- python - 使用“扁平化”索引访问 2D 列表的好方法是什么?
- r - 如何将报价和交易数据与 data.table 匹配(滚动连接)
- jq - 使用jq在终端使用telnet美化输出
- typescript - javascript中的方法头中如何使用冒号(“:”)?