Get route parameters Angular?

自作多情 提交于 2019-12-30 07:49:23

问题


Routing rules are:

const routes: Routes = [{
    path: "",
    component: SkeletonComponent,
    children: [{
      path: "dictionary",
      component: DictionaryComponent,
      children: [
        {
          path: ":dict/:code",
          component: VersionsComponent
        }]
}];

URL looks like:

http://localhost:4200/dictionary/Gender/5

Where Gender is parameter: :dict and 5 is parameter :code.

I tried to get parameters inside component VersionsComponent:

ngOnInit() {
    console.log(this.activateRoute.snapshot.params['dict']);
    console.log(this.activateRoute.snapshot.params['code']);
}

I always get undefined


回答1:


The most effective way (works in all scenarios) is to subscribe to Activated Route. It'll work even when you don't switch between components, and only change the parametarised portions of the URL.

this.activatedRoute.params.subscribe(
  (params: Params) => {

    console.log(params.dict)

  }
)

If you don't subscribe to params, the code will only work when the component is loaded initially. After that, you need to leave the component for it to work again. By subscribing, you can load multiple resources without ever leaving the component.




回答2:


As mentioned above go with paramMap. Please refer the stackblitz

  ngOnInit() {
    this.activatedRoute.paramMap.subscribe((data)=>{
      console.log(data.params)
    })
  }



回答3:


i think Your Routes configuration is wrong, should be like that:

const routes: Routes = [
  {
    path: '',
    component: SkeletonComponent
  },
  {
    path: "dictionary",
    component: DictionaryComponent,
    children: [{
      path: ":dict/:code",
      component: VersionsComponent
    }]
  }
];

and make sure on DictionaryComponent your using <router-outlet>



来源:https://stackoverflow.com/questions/57679513/get-route-parameters-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!