Home > Software design >  How to get "previous" url param in angular?
How to get "previous" url param in angular?

Time:05-23

I have a Routes constant as below and I need to get a configurationId param in ngOnInit inside the MachineGroupComponent. this.route.snapshot.paramMap.get('configurationId') returns null.

How can I do it?

const routes: Routes = [
  {
    path: '',
    component: ConfigurationsComponent,
    children: [
      {
        path: '',
        component: ConfigurationsListComponent
      },
      {
        path: ':configurationId',
        component: ConfigurationComponent,
        children: [
          {
            path: '',
            component: MachineGroupsComponent
          },
          {
            path: ':machineGroupId',
            component: MachineGroupComponent
          },
        ]
      },
    ]
  },

];

CodePudding user response:

I had the same problem, add paramsInheritanceStrategy: 'always' on your app-routing.module.ts and you'll be able to get the previous router params normally.

Like this:

@NgModule({
  imports: [RouterModule.forRoot(routes), RouterModule.forRoot(routes, {
    paramsInheritanceStrategy: 'always'
})],
  exports: [RouterModule],
})

You have the documentation here in case you want to read more about.

CodePudding user response:

to get the param value you can use ActivatedRoute

constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
    let param = params['yourParam'];
    console.log(param); 
});
}

CodePudding user response:

We can traverse activatedRoute to get parent params

Try this

 ngOnInit() {
    this.activatedRoute.root.firstChild.root.firstChild.firstChild.paramMap.subscribe(
      (params) => {
        console.log(params.get('configurationId'));
      }
    );
  }

CodePudding user response:

Try this

ngOnInit() {
    // Get parent ActivatedRoute (this.route) of this route.
    this.route.parent.params.forEach((params: Params) => {
        this.configurationId =  params["configurationId"];
    });
}
  • Related