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

时间:2019-08-12 07:58:36

标签: angular redirect routing angular-resolver

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

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

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:

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上触发重定向->对我来说有点臭

1 个答案:

答案 0 :(得分:0)

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

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