我激活的路由未在url中找到参数。我该如何解决?

时间:2019-07-04 08:30:30

标签: angular

我正在尝试制作一个有角度的Web应用程序,并且路由器似乎无法正常工作。我希望它在输入URL时找到id和studentId。

在app-routing.module.ts中,我有这些溃败

{path: "Classes", component: ClassListComponent, children : [
    {path: ":id",
    children:[
      {path: '', component: StudentListComponent, pathMatch: 'prefix',
      children : [
        //{path: '', component: TableComponent, pathMatch: 'full'},
        {path: ':studentId/TimeTable', component: TableNavComponent, children: 
        [
          {path:'', component: TableComponent},
        ]},
      ]},
    ]},
  ]}

例如,当我输入http://localhost:4200/Classes/1/5/TimeTable时 我希望能够以1的价格获得activatedRout.params['id'](或任何其他获取参数的方法),但是当我将其登录到浏览器的控制台中时,会收到undefined。尽管studentId很好。 对于我添加的其他任何参数,只会返回最后一个参数。

这是表代码的最新版本:

ngOnInit() 
  {
    this.rout.paramMap.subscribe(
      param=> {
        if(param.has('studentId'))
        {
          this.studentId = param.get('studentId');
          console.log(this.studentId);
          this.data.StudentId = this.studentId;
        }
        if(param.has('id'))
        {
          this.ClassId = param.get('id');
          console.log(this.ClassId);
          this.data.ClassId = this.ClassId;
        }
        this.data.initTable(this.studentId);
    }
    )

    }

在控制台中,我只收到5,即StudentId,并且没有id的迹象。

1 个答案:

答案 0 :(得分:0)

有很多方法可以获取参数

1:从快照读取

const routeParams = this.activeRoute.snapshot.params;
console.log(routeParams.id);

2:通过订阅

this.activeRoute.params.subscribe(routeParams => {
        console.log(routeParams.id);
});