首页 > 解决方案 > 如何根据解析的路由数据路由到子路由?

问题描述

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

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

应用模块:

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

如何根据提供的数据重定向到路由?我可以使用任何路由挂钩吗?

通过:

标签: angularredirectroutingangular-resolver

解决方案


您可以评估下一步需要做什么,然后导航到特定路线:

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

推荐阅读