首页 > 解决方案 > Angular:在路由中传递可选数据

问题描述

我正在使用angular 5,我有一个很长的路由文件:

const homeRoutes: Routes = [
  {
    path: 'home', component: HomeComponent,
    children: [
      {
        path: 'registration',
        component: RegistrationComponent,
        children: [
          {
            path: 'synthese',
            component: SyntheseComponent
          },
          {
            path: 'queue',
            component: QueueComponent,
            children: [
              {
                path: 'queue-modal',
                component: QueueModalComponent
              },
              {
                path: 'confirm',
                component: ConfirmComponent
              }
            ]
          }
        ]
      },
      {
...

我想在“注册”路径中传递数据。

有人告诉我,我需要这样写: path: 'registration/:mydata'

然后订阅ActivatedRoute的数据

我并不总是传递数据的问题,它只是在某些情况下。

我怎样才能以最小的影响做到这一点?

标签: javascriptangulartypescriptangular5angular-routing

解决方案


您可以使用查询字符串参数(AKA queryParams)代替路由参数。您不需要在路由中定义查询参数。

以下是相对 href 的示例:

registration/?mydata=123

这是您可以queryParams为 a定义的方式routerLink

<a [routerLink]="['registration']" [queryParams]="{ mydata: 123 }">Go to Registration</a>

这是您可以读取该参数值的方式:

myValue: any;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    this.myValue = params['mydata'];
  });
}

推荐阅读