Why is it that when using Angular, history.state.data returns undefined rather than the previously set data object?

I'm working with a table of orders. Each row in the table represents an order entity, and I want to redirect the user to a new view with the details of the clicked order when they click on a specific row. The two components are not parent and child elements, so I need to find a way to pass data about the clicked order row to the navigated page. I attempted 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 results in the view navigating to Orderdetails.

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

Upon checking inside the ngOnInit() function, console.log(history.state) shows {navigationId: 1}, while console.log(history.state.data) returns undefined. Why am I only seeing undefined instead of the data I set for the state property? How can I retrieve and access the data that I passed into the state property?

Answer №1

After conducting some research, it was discovered that state does not function on non-anchor elements.

To address this issue, state can be used when routing programmatically:

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);
}

Answer №2

Encountering the same issue, I found that History.state was mysteriously empty upon navigating to the next component. After some investigation, I discovered that the root cause was my inadvertent execution of

_router.navigate([] {relativeTo: this._activatedRoute, queryParams: {search: searchqueryparams}, queryParamsHandling: 'merge'}) 

from within a subscription in the constructor during page load. This code snippet was meant to persist any search query parameters to the URL. It appears that the router.navigate function overrides the old history state even if the component remains unchanged. By simply storing the old state before navigating again, I managed to resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NextJS and AWS Amplify collaboration for secure authentication routing

After hours of research, I'm struggling to navigate the authentication routing in NextJS combined with AWS Amplify. As a newcomer to NextJS, I want to implement a feature that disables the login/register page for users who are already logged in and pr ...

Tips for determining if a JavaScript cookie has expired

Is it possible to check if a javascript cookie has expired using? I have some conditional tasks to accomplish, and two of those conditions are overlapping. It would be more convenient for me if I could determine if a cookie has expired. Currently, I am u ...

Numerous unresolved peer dependency issues have been detected, such as a missing @angular/[email protected]

I've been encountering issues with package dependencies lately, specifically related to angular2-busy. However, upon further investigation, it seems like there may be a larger underlying problem. Whenever I execute "npm list", I am bombarded with UNM ...

What is the reason behind div elements shifting when hovering over a particular element?

Currently, I have floated all my div elements (icons) to the left and margin-lefted them to create space in between. I've displayed them inline as well. However, when I hover over one element (icon), the rest of the elements move. Can you please help ...

Identify classes within an Angular 5 material list that contain odd and even elements

Currently utilizing the Angular Material data table and curious about how to incorporate odd and even classes. ...

Disable Dates in Material UI Date Textfield

Is there a way to prevent users from selecting dates between the specified Min and Max dates in a material UI date textField? For example, if the minimum date is today's date 01/30/2023 and the maximum date is next month's date 02/30/2023, I wou ...

Encountering the error message "Uncaught TypeError: $.ajax is undefined"

Recently, I encountered an issue with my form that utilizes ajax to send user information to a php file. The form is embedded within a bootstrap modal and was functioning perfectly until I attempted to add an extra field for enhanced functionality. However ...

Unable to navigate to different pages using Angular material's flex-layout sidenav

Seeking assistance on how to navigate to different pages when clicking on hyperlinks (whether the browser is full window or not, with the menu at the top right corner). Check out this StackBlitz. Is it necessary to use mat-sidenav-content fxFlexFill and ...

When executing JavaScript code with an Ajax HTTP request, the output displayed is 2 but the

I'm currently working on a local chat application and encountering an issue where it displays an undefined result before properly showing all data. Below is the code snippet: function chatDisplay(){ if(mainchat.msg.value== ""){ a ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

Steps to display a single entry in a Laravel/Vue implementation

My goal is to combine Laravel with Vue and eventually Nuxt in order to incorporate dynamic page transitions similar to the ones showcased on into my websites. I recently followed a tutorial on using Vue with Laravel at https://scotch.io/tutorials/build-a ...

Error: JSON parse error - unexpected character 'a' at index 1

I'm encountering an issue while attempting to change the album title from "cars" to "car". The error message I keep receiving is: SyntaxError: Unexpected token a in JSON at position 1. Any ideas on what might be causing this problem? Below is the cu ...

What is the best way to implement the hamburger-react-menu exclusively for mobile or small screen users?

Looking to implement a mobile menu in my component, specifically for mobile devices. The menu should display options like Home, Furniture Chair... when clicked on the hamburger icon. I have the hamburger-react-menu package installed but unsure whether to u ...

Guide to setting FileReader base64 as a variable

I attempted to print the base46 data and here is how it appears: var fileData; var files = document.getElementById('pickUpFileAttachment').files; if (files.length > 0) { var promise = getBase64(files[0]); promise.then(function (resul ...

What is the best way to choose the nearest element using the initial part of a class name?

I am working on a section of a table and need to hide a specific part when an icon is clicked. Below is the code snippet: <tr class="getmoreinfo_19"> <td>&nbsp;</td> <td colspan="3"> <div c ...

Using Angular and pascalprecht.translate to convert JSON to HTML with a line separator

Excuse my poor English in advance. I'm encountering an issue with displaying a line separator on my HTML page. I'm using AngularJS with the translate module pascaleprecht.translate. I want to include a line separator within a translation. ...

A mysterious JavaScript snippet that automatically scrolls down when the webpage is loaded

Recently, I encountered an issue with a mysterious JavaScript script that automatically scrolls down when entering the page (I suspect it's JavaScript). I've tried to investigate using Firebug, examining the code, deleting scripts, and even remov ...

Using Angular2 to assign the response from an http.get request to a class object

I am a beginner in Angular and I have a JSON file that holds the configuration URL for my application. Path: app/config/development.json { "apiUrl": "http://staging.domain.com:9000/", "debugging": true } Below is the content of my config.service.t ...

ExitDecorator in TypeScript

Introduction: In my current setup, I have an object called `Item` that consists of an array of `Group(s)`, with each group containing an array of `User(s)`. The `Item` object exposes various APIs such as `addUser`, `removeUser`, `addGroup`, `removeGroup`, ...

What is the best way to execute a command after the file system has finished writing to a file?

Below is the code under scrutiny: const scriptFiles = fs.readdirSync(scriptsPath) .filter(file => file.endsWith(".sql")); for (const file of scriptFiles) { var data = fs.readFileSync(`${scriptsPath}/${ ...