簡體   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