Modify data object in ActivatedRoute

后端 未结 3 1480
無奈伤痛
無奈伤痛 2020-12-19 22:04

I need to modify the breadcrumb value in the data object of my current route. Here is my route configuration.

      {
    path: \"users\",
    component: Us         


        
3条回答
  •  难免孤独
    2020-12-19 22:43

    I had a similar problem and followed the advice here: https://github.com/angular/angular/issues/13860#issuecomment-271884682

    Basically, the idea is that you don't define the children of the router immediately, but delay that. So, in your Routes above, just set children: [] and take that data and put it in another Routes object in the UserListComponent. Then, in that component you have something like the following for your constructor:

    constructor(activatedRoute: ActivatedRoute) {
        activatedRoute.routeConfig.children = routes;
    }
    

    So, putting it all together, two files are involved and we end up with:

    // user-routing.module.ts
    const routes = [
      {
        path: "users",
        component: UserListComponent,
        children: [],
        data: {
          breadcrumb: 'Users'
        }
      }
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    export class UserRoutingModule {
      constructor() { }
    }
    

    and

    // user.component.ts
    const routes = [
      {
        path: ":id",
        component: UserComponent,
        data: {
          breadcrumb: ''
        },
      }
    ];
    @Component({
      selector: 'app-user',
      templateUrl: './user.component.html'
    })
    export class UserComponent {
      constructor(activatedRoute: ActivatedRoute) {
        routes[0].data.breadcrumb = 'Bob Johnson';
        activatedRoute.routeConfig.children = routes;
      }
    }
    

    This allows you to pass what appears to be dynamic, or late-bound, data to the router since you have an instantiated class with dependencies injected with which you can do any manipulation you want on the data before attaching it to the router.

提交回复
热议问题