Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: history.state.data returns undefined instead of the last set data object?

I have a table of orders..each table row represents an order entity and when the user clicks on a specific row, it should redirect to a new view with the details of the clicked order .These two components are not parent and child and I want to pass data about clicked order row to the navigated page.. I tried the following approach

 <tr *ngFor="let order of allOrders" routerLink="../orderdetails" [state]=”{data:order}”>
                <td>{{order.orderRef}}</td>
                <td>{{order.receiptRef}}</td>
                <td>{{order.customer}}</td>
                <td>{{order.orderDate}}</td>
                <td>{{order.salesMan}}</td>
                <td>{{order.total}}</td>
                <td>{{order.status}}</td>
                <td>{{order.session}}</td>
                <td>
                </td>
              </tr>

This causes view to navigate to Orderdetails

 ngOnInit(): void {
    console.log(history.state)
    console.log(history.state.data);
  }

Inside the ngOnInit() console.log(history.state) logs {navigationId: 1} but console.log(history.state.data) logs undefined.

Why am I getting undefined and not the data I set on the state ?

How can I access the data I passed in to the state property?

like image 829
Arjun Avatar asked Dec 13 '22 09:12

Arjun


1 Answers

Upon some research, I found that state doesnt work on non-anchor elements.

To solve the issue, On routing programatically we can use state:

orders.html

<tr *ngFor="let order of allOrders" (click)="onNavToOrderDetails(order)">
   <td>{{order.orderRef}}</td>
   <td>{{order.receiptRef}}</td>
   ....
</tr>

orders.ts

import { Router } from '@angular/router';

constructor(
   private router: Router
) {}

onNavToOrderDetails(order: Order) {
   this.router.navigate(['routetodetailscomponent'], { state: {data: order} });
}

orderDetails.ts

ngOnInit(): void {
   console.log(history.state)
   console.log(history.state.data);
}
like image 167
Gangadhar Gandi Avatar answered Dec 29 '22 06:12

Gangadhar Gandi