简体   繁体   English

使用Angular2将数据传递到路由组件中

[英]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. 基本上,home组件具有仅适用于该组件的子路由。 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 然后,您可以通过ActivatedRouteSnapshot访问customerId

eg. 例如。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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