Passing parameter from parent to child component when using hierarchical routes with Angular2

主宰稳场 提交于 2019-12-12 04:14:41

问题


I have a route config as following:

export const ProjectRoutes: Route[] = [
  {
    path: 'projects',
    component: ProjectComponent,
    canActivate: [ScrollTop, AuthGuard],
    data: {
      roles: [Role.USER]
    }
  },
  {
    path: 'project/:id',
    component: ProjectDetailsComponent,
    children: [
      {
        path: '',
        component: ProjectInfoComponent,
        canActivate: [ScrollTop, AuthGuard],
        data: {
          roles: [Role.USER]
        }
      },
      {
        path: 'tools',
        component: ProjectToolsComponent,
        canActivate: [ScrollTop, AuthGuard],
        data: {
          roles: [Role.USER]
        }
      }
    ]
  }
];

Where the template of ProjectComponent is:

<div class="container-fluid">
  <div class="row">
    <div class="col-md-2">
      <priz-project-nav [project]="project"></priz-project-nav>
    </div>
    <div class="col-md-10">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

Now, as you can see, the priz-project-nav requires a project to render the navigation, but also ProjectInfoComponent and ProjectToolsComponent do.

So, what I am forced to do now is to load project object in each component separately, including in the parent one. My question is, is it possible to pass loaded once object between components while each and every one of the child components is set under it's own route?


回答1:


Shared Service would be the way to go:

@Injectable()
export class YourSharedService {
    sharedRole: {
        // your properties here... e.g
        name: 'string'
    };
}

and inject that service in the constructor to all components that need to have access to the shared objec (or whatever)

constructor(private yourSharedService: YourSharedService......) {  }

Then you can access it in every component like so:

localRole = this.yourSharedService.sharedRole;

and assign new values to it:

this.yourSharedService.sharedRole = localRole

and this goth bothways. All components that are assigned with this shared object get the value updated automatically if you make changes to it in some component.

The above is one solution. There are naturally other solutions ass well, e.g using Observables. More info about that is found in the angular doc - component interaction I highly suggest you check out the doc in other issues too, the tutorial is very good in my opinion :)



来源:https://stackoverflow.com/questions/41511959/passing-parameter-from-parent-to-child-component-when-using-hierarchical-routes

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