Angular4:router,children(可选)参数

时间:2017-06-08 11:47:43

标签: angular router

所以,我希望产生这样的路径:

  

匹配/:页/:团队/:季节

其中:team和:season是可选参数 所以我可以有一个像

这样的网址
matches/results/4/2017 or
matches/results/4 or
matches/results

所有内容都应该有效,并在this.route.snapshot.params

中通过

我试过了:

  {path: 'matches', children: [
    {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
    {path: 'competitions', component: CompetitionsPageComponent},
    {path: ':page', component: PageComponent, children: [
      {path: ':team', children:[
          {path: ':season', children:[]}
      ]}
    ]},
  ]},

没有运气,只有:页面来自param

3 个答案:

答案 0 :(得分:3)

我认为你想要考虑的事情是你真的想要儿童路线还是只是同一页面或每个级别?另一个例子将最终呈现两个组件......这可能是你想要的,但如果没有,那么你可能会拼出每个组件。

{ path: 'matches/results/', component: ResultsComponent, },
{ path: 'matches/results/:page/', component: PageComponent, },
{ path: 'matches/results/:page/:team/', component: TeamComponent, },
{ path: 'matches/results/:page/:team/:season', component: PageComponent, },

还要注意您在路径中使用的名称是您需要在param选择器中使用的名称:

params['page']
params['team']
params['season']

示例代码

this.route.params.subscribe((params) => {
    this.teamService.getTeam(params['team']).subscribe((team) => {
        this.team = team;
    });
});

答案 1 :(得分:2)

考虑以下结构:

const paths: Routes = [
  {
    path: 'matches',
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'fixtures' },
      { path: 'fixtures', component: FixturesComponent },
      { path: 'competitions', component: CompetitionsPageComponent },
      {
        path: ':page',
        component: PageComponent,
        children: [
          {
            path: ':team',
            component: TeamComponent
            children: [
              {
                path: ':season',
                component: SeasonComponent,
                children: [

                ]
              }
            ]
          }
        ]
      }
    ]
  }
];

根据您注入ActivatedRoute的组件,您将能够访问不同的路由参数。例如

如果您在ActivatedRoute中注入SeasonComponent并执行以下操作:

this._route.params.subscribe(p => console.log(JSON.stringify(p)));

您将看到由页面,团队和季节属性组成的对象。

如果对PageComponent执行相同的操作,您将获得一个仅由一个属性页面组成的对象。如果您明白了,如果您在ActivatedRoute中注入TeamComponent,参数将只有2个属性。

您收听路由器事件然后读取ActivatedRoute实例中的属性这一事实不会产生影响,因为ActivatedRoute类的注入实例包含生成在注入实例的组件时路径中存在的参数。

所以基本上,至少采用这种方法,不可能从组件层次结构中某个级别的组件进行访问,以便在其中进一步路由参数。

希望它有所帮助!

答案 2 :(得分:0)

@ user2623919答案足够接近......

这对我有用...所有路线都指向同一个PageComponent,在我的参数中我得到了我设置的那些.... 这样

{path: 'matches', children: [
  {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
  {path: 'competitions-table', component: CompetitionsPageComponent},
  {path: ':page', component: PageComponent},
  {path: ':page/:team', component: PageComponent},
  {path: ':page/:team/:competition', component: PageComponent},
  {path: ':page/:team/:competition/:season', component: PageComponent}
]},
  

/匹配/结果

给了我{s} {page: 'results'}

  

/匹配/结果/ 20

给我params {page: 'results', team: '20'}等等

干杯球员

相关问题