简体   繁体   中英

Passing data into a routed component with Angular2

I have a component that's loaded via routing and I'm trying to pass data into the component from a parent component. How would I go about doing this?

Parent Component Class

export class HomeComponent{
    userName: string;
    userId: string;

    ngOnInit(): void{
        this.userName = "user name";
        this.userId = "user id";
    }
}

Parent Component Template

<div>
    <p>Parent Component</p>
</div>
<router-outlet></router-outlet>

Child Component Class

export class ChildComponent{
    userName: string;
    userId: string;
}

Basically, the home component has child routes that are only available to that component. The child component is automatically loaded along with the parent component, but I want to use the data from the parent component, inside the child component. For practicality purposes and not having questions about whether my application is set up correctly, it is.

You can pass variables via the Router if you want to, eg.

const routes = 
[                                                                                     
    { path: "child/:customerId", component: ChildComponent },                                                               
]

Then you can access customerId via the ActivatedRouteSnapshot

eg.

class ChildComponent
{
  constructor(route : ActivatedRouteSnapshot)
  {
    const customerId = +route.params["customerId"];
  }
}

为服务提供反应性数据是最好的解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM