简体   繁体   English

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

[英]How can I route to a child route based on the resolved route data?

I'm loading a module with data from the resolver. 我正在使用来自解析器的数据加载模块。 The loaded module has the usual empty-path redirect to the first child route. 加载的模块具有通常的空路径重定向到第一个子路由。 But I want to redirect to a specific route based on the resolved data. 但我想根据已解析的数据重定向到特定的路由。

In the current example I have a child module with three components. 在当前示例中,我有一个包含三个组件的子模块。 The Resolver in the root module provides the data to which component should be redirected to. 根模块中的解析器提供了应将组件重定向到的数据。

AppModule: AppModule:

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 { }

ChildModule: ChildModule:

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 { }

The Resolver returns the step that should be redirected to 解析程序返回应重定向到的步骤

@Injectable({
  providedIn: 'root'
})
export class StepResolver implements Resolve<string> {
  resolve(route: ActivatedRouteSnapshot): Observable<string> {
    return of('step2');
  }
}

How can I redirect to the route based on the provided data? 如何根据提供的数据重定向到路由? Are there any routing hooks that I can use? 我可以使用任何路由挂钩吗?

Throughts: 穿透次数:

  • CanActivate on the empty child path -> CanActivate is called after provide, so: no data 空子路径上的CanActivate->在提供之后调用CanActivate,因此:无数据
  • load an empty component in empty child path and trigger the redirect at OnInit -> a bit smelly for me 在空的子路径中加载一个空的组件,并在OnInit触发重定向->对我来说有点臭

You could evaluate what next step is necessary and then navigate to the the specific route: 您可以评估下一步需要做什么,然后导航到特定路线:

this.route.navigate([yourStep]);

You would have to import Router : 您将必须导入Router

constructor(private route: Router) { }

Edit: 编辑:
Create a service with something like this: 使用以下内容创建服务:

goToStep(step: string) {
  this.route.navigate([step]);
}

And the resolver considering the code you provided: 解析器考虑您提供的代码:

resolve(route: ActivatedRouteSnapshot): Observable<string> {
   return this.stepService.goToStep('step2');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM