如何根据解析的路由数据路由到子路由?



我正在用解析器中的数据加载模块。 加载的模块具有通常的空路径重定向到第一个子路由。但是我想根据解析的数据重定向到特定路由。

在当前示例中,我有一个包含三个组件的子模块。 根模块中的解析程序提供应将组件重定向到的数据。

应用模块:

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');
}

最新更新