![](/img/trans.png)
[英]Data passed from an Angular parent component to a child component is undefined in child component
[英]Angular: data passed from another component becomes undefined on the page reload
在我的 angular 應用程序中,我需要一個組件將數據傳遞給另一個沒有父子關系的組件。我在一個組件中有一個Orders table
,每一行代表一個訂單。 當用戶單擊任何特定行時,我需要導航到 OrderDetails 組件並傳遞表示單擊行的訂單對象
驗證.component.html
<tr *ngFor="let order of allOrders" (click)="onNavToOrderDetails(order)">
<td>{{order.id}}</td>
</tr>
驗證.component.ts
onNavToOrderDetails(order) {
this.router.navigate(['orderdetails'], { state: {data: order} });
}
orderdetails.component.ts
order;
ngOnInit(): void {
this.order=history.state.data;
console.log(this.order);
}
訂單詳情.component.html
<p>{{order.id}}</p>
orderdetails.component.html
在從validation.component.html
導航時顯示訂單 ID,但刷新訂單詳細信息頁面會導致訂單 ID 消失。 我了解頁面刷新history.state.data
變為未定義但如何解決此問題? 由於該應用程序是 SPA,因此將來自validationcomponent
的數據存儲到服務並在orderdetailscomponent
使用該服務也不起作用。
頁面刷新意味着重新加載整個 angular 應用程序,驗證組件存儲在服務中的訂單對象也將消失。 如何解決這個問題? 我希望先前存儲在服務中的數據不受影響並在頁面重新加載時再次顯示?
有3種處理方法:
sessionStorage
(不要使用 localStorage),但要確保按照場景維護 sessionStorage 數據ngOnInit(): void {
if(history.state.data){
this.order=history.state.data;
sessionStorage.setItem('order_page_info', JSON.stringyfy(this.order));
}else{
this.order = JSON.parse(sessionStorage.getItem('order_page_info'))
}
}
id
作為路由器數據傳遞並進行服務器調用以獲取id
詳細信息。 這將在 url 中維護id
,因此您可以通過調用服務器獲取刷新的詳細信息嘗試將 ngOnChanges
ngOnChanges 檢測來自其他組件的更改,特別是從服務的 api 調用
ngOnChanges(){
this.order=history.state.data
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.