Retrieve the additional navigation information using Angular's `getCurrentNavigation()

I need to pass data along with the route from one component to another and retrieve it in the other component's constructor:

Passing data:

this.router.navigate(['/coaches/list'], {
          state: { updateMessage: this.processMessage },
          replaceUrl: true
        });

Retrieving data in the constructor:

if (this.router.getCurrentNavigation().extras?.state != null) {
  this.successMessage = this.router.getCurrentNavigation().extras.state;
}

The issue I am facing is that initially, extras.state is undefined without any data. It only gets populated when I close the dialog button on the other component.

How can I resolve this problem as I keep getting the ERROR TypeError: Cannot read property 'extras' of null during the initial loading?

Answer №1

To retrieve the state, use the following method:

history.state.updateMessage

Answer №2

After troubleshooting, I successfully fixed the problem by verifying if the getCurrentNavigation is not null:

    constructor(
    private fb: FormBuilder,
    private modalService: NgbModal,
    private route: ActivatedRoute,
    private router: Router,
    public commonService: CommonService
  ) {
    if (this.router.getCurrentNavigation() != null) {
      this.successMessage = this.router.getCurrentNavigation().extras.state;
    }
  }

Answer №3

To condense this into one line of code, you can set your message to null if getCurrentNavigation() returns falsy:

this.successMessage = this.router.getCurrentNavigation()?.extras.state;

Alternatively, you can assign a default value like 'YOUR VALUE' if the state is empty:

this.successMessage = this.router.getCurrentNavigation()?.extras.state ?? 'YOUR VALUE';

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

Is it necessary to incorporate the OnInit function in Angular 8+ components if I have no intention of modifying it?

I've been working on a project using Angular 8. One thing I've noticed is that when I use the command line to generate components, they are automatically created with OnInit included. For example: export class SideDrawerComponent implements On ...

Displaying rows in a mat-table based on a certain condition

Is there a way to only display data in the table if the status is 'done'? I attempted to remove the status, but it still shows the row. Any suggestions on how to achieve this? data { equipmentOrdered: 'laptop', qty: 1, s ...

SCORM-compliant Angular web application bundle

As I work on my angular web project, I am looking to create a SCORM package in order to easily integrate it into any LMS system. I have a few questions regarding the packaging process and compatibility: What is the best way to package my project for SCORM ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Learn how to send an SMS using Angular and Ionic 4 without having to open the native SMS app

I have been actively monitoring the GitHub repository for the Ionic Native SMS plugin at https://github.com/cordova-sms/cordova-sms-plugin. Following the suggested configuration from the repo, I have set it up as follows: var options = { repla ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

What's the best way to implement satisfies with a generic type?

In my development process, I am working with components that have default values combined with props. To streamline this process, I created a single function for all components: export function getAssignProps <T extends {}>(propsMass:T[]){ return ...

A guide to turning off tab discarding in Google Chrome with JavaScript

Is there a way to prevent Chrome from discarding tabs on chrome://discards/ using JavaScript so that the tab remains open even after closing the page or browser? I am aware that this can be achieved with an extension, but I am interested in creating my o ...

Combining a pair of canvases

Currently, I am utilizing a JavaScript library to create a QR Code. This library generates the QR code by displaying it on a canvas. Nevertheless, my goal is to integrate a background behind this QR Code. I attempted to achieve this by first drawing the b ...

Avoid Angular 6 router from taking precedence over routes set in Express Server

What is the best way to ensure that Angular routing does not conflict with routes from an Express Node Server? In my Express server, I have set up some routes (to node-RED middleware) as follows: server.js // Serve the editor UI from /red app.use(settin ...

What is the best way to retrieve both the checked and unchecked values from a collection of checkboxes?

Check Out This live Example: I am in the process of creating a list of checkboxes with various data objects: data = [ { Key: "class_id", displayName: "Section ID", enabled: true }, { Key: "room_l4", displayName: "Location", enabled: false }, { Key: "se ...

Utilizing Angular to augment existing items in local storage

Hey everyone, I'm facing an issue with localStorage that I can't seem to figure out. I have a form where the first step collects name and gender, and the second step asks for weight and height. The data from step 1 is saved in localStorage, but ...

Encountered Angular 7 Error: Unable to access pro due to TypeError

I've encountered an error in my Angular front-end application: Error: index.js:3757 TypeError: Cannot read pro Here's what I have tried so far: I inspected the code but couldn't find the root cause of the error. Running "Ng build" r ...

Different Approaches for Handling User Interactions in Angular Instead of Using the Deferred (Anti-?)Pattern

In the process of developing a game using Angular, I have implemented the following mechanics: An Angular service checks the game state and prompts a necessary user interaction. A mediator service creates this prompt and sends it to the relevant Angular c ...

Issue with Angular 2: MaterializeCSS module not loading correctly when using routing

I am currently incorporating MaterializeCSS into my Angular project. It appears that materialisecc.js and/or jquery.js are loaded with routing, causing the need to reload each page of the app for it to function properly. This issue is affecting the overall ...

ERROR Error: Uncaught (in promise): ContradictionError: The variable this.products is being incorrectly identified as non-iterable, although it

Seeking a way to extract unique values from a JSON array. The data is fetched through the fetch API, which can be iterated through easily. [please note that the product variable contains sample JSON data, I actually populate it by calling GetAllProducts( ...

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

ng2-order-pipe fails to apply sorting when objects are added or removed

I have set up my application to display a div for each object in an array, utilizing the ng2-order-pipe to arrange them accordingly: <div class="patients-container" (dragover)="allowDrop($event)" (drop)="onDrop($event)"> <div class="patient-box ...

"Type 'Unknown' cannot be assigned to the specified type: Typescript Error encountered while using

I encountered an error message in my Redux Observable setup. Any advice on how to resolve this issue? The error states: 'Argument of type 'OperatorFunction<ITodo[], Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; ...

Issue with Destructuring Assignment Syntax in TypeScript

interface User extends Function { player: number, units: number[], sites: string[], } class User extends Function { constructor() { super('return this.player') [this.player, this.units, this.sites] = getBelongings( ...