Search code examples
angularangular-routing

Angular RouterModule.forRoot - access route path parameter, and pass it down to route data


I need to set the data of a route in my angular module:

@NgModule({
    imports: [
        RouterModule.forRoot(
            [
                {
                    component: ManageProjectReleaseStageComponent,
                    path: 'ng-projects/:id/releases/:releaseId',
                    data: {
                        breadcrumb: 'View Release',
                        breadcrumbPredecessors: [
                            { label: 'Project Search', url: '/ng-projects/search' },
                            { label: 'View Project', url: '/ng-projects/:id/view' }
                        ]
                    }
                },

I need to get the id parameter out of this bit here: path: 'ng-projects/:id/releases/:releaseId',, and pass it into this bit here: { label: 'View Project', url: '/ng-projects/:id/view' }

Because right now it is just passing the string: ":id".

How can I access the :id parameter from the path, to pass it into the data?.


Solution

  • You can access the router instance and fetch its params by using Resolvers instead of the router static data

    breadcrumb.resolver.ts

    @Injectable({ providedIn: 'root' })
    export class BreadcrumbResolver implements Resolve<any> {   
                                                                                                    
      constructor() {}
    
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
          // Get :id from the route
          const projectId = route.params.id; 
    
          // Initialize and Return this data
          const breadcrumb = {
              breadcrumb: 'View Release',
              breadcrumbPredecessors: [
                 { label: 'Project Search', url: '/ng-projects/search' },
                 { label: 'View Project', url: `/ng-projects/${projectId}/view` }     // Pass your ID value from the route
              ]
          }
    
          return breadcrumb;    
      }
    
    }
    

    RouterModule

    RouterModule.forRoot([
         {
            component: ManageProjectReleaseStageComponent,
            path: 'ng-projects/:id/releases/:releaseId',
            resolve: {
               breadcrumb: BreadcrumbResolver
            }
            
         },
         ...
    ])
    

    ManageProjectReleaseStageComponent

    @Component({...})
    export class ManageProjectReleaseStageComponent implements OnInit {
    
        constructor(private route: ActivatedRoute) {}
    
        ngOnInit(): void {
           const breadcrumb = this.route.snapshot.data.breadcrumb;    // Access your breadcrumb value
           console.log(breadcrumb);          
        }
    
    }
    

    Have created a Stackblitz Demo for your reference