繁体   English   中英

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

[英]Passing data into a routed component with Angular2

我有一个通过路由加载的组件,并且正在尝试将数据从父组件传递到该组件中。 我将如何去做呢?

父组件类

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

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

父组件模板

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

子组件类

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

基本上,home组件具有仅适用于该组件的子路由。 子组件会与父组件一起自动加载,但是我想使用子组件内部来自父组件的数据。 出于实用目的,我对应用程序的设置是否正确没有疑问。

您可以通过路由器传递变量,例如。

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

然后,您可以通过ActivatedRouteSnapshot访问customerId

例如。

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

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

暂无
暂无

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

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