[英]How to pass data between routed components in Angular
使用路由
如果你想使用路由將數據從一個組件傳遞到另一個組件,你可以使用NavigationExtras
。
在 CompA 中,您可以:
constructor(private router: Router){
}
goToCompB(){
this.router.navigate(['associate-product/' + this.id], {
state:{
data: yourDataToShareWithCompB
}
});
}
在 CompB 你可以這樣做:
constructor(private router: Router){
const data = router.getCurrentNavigation().extras.state.data;
}
PS:您也可以使用其他人回答的基於服務的模式
您可以使用帶有主題/行為的服務來實現這一點,如他們的文檔中所述
使用服務,您可以通過注入服務的組件共享數據。
我創建了一個stackblitz ,其中有一個小例子可以共享數據並知道何時從 API 檢索數據。
在此示例中,您有 2 個組件 A 和 B,以及一個服務“example”。
在你的第一個組件 (A) 上,你調用 API 來獲取數據,在這個例子中,我做了一個 seTimeout 來模擬異步調用。
然后,當調用結束時,可以顯示一個移動到 b 的按鈕,並且在組件 b 上有從超時中檢索到的數據。
可以使用NavigationExtras
中的state
object 。 就像其他人提到的
this.router.navigate(['your-component-route'], {
state:{
myComplexObject: dataObject
}
});
然后在其他組件中獲取 object
constructor(private router: Router){
const data = router.getCurrentNavigation().extras.state.myComplexObject;
}
**
** 這里值得一提的是,這個router.getCurrentNavigation()
只在**constructor**
中有值,否則在onInit中是訪問不到的。 希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.