Passing parameter from parent to child component w

2019-09-18 04:57发布

问题:

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 :)