Search code examples
angularangular7angular8

Get route parameters Angular?


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


Solution

  • 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.