After upgrading to Angular 15, the Router getCurrentNavigation function consistently returns null

Since upgrading to angular 15, I've encountered a problem where the this.router.getCurrentNavigation() method is returning null when trying to access a state property passed to the router. This state property was initially set using router.navigate in another component.

In Component A:

https://i.stack.imgur.com/zs5DS.png

In Component B:

https://i.stack.imgur.com/tR941.png

I am able to access the state in Component B by using this.state = history.state;. However, the code

this.state = this.router.getCurrentNavigation()?.extras?.state ?? {};
does not work as getCurrentNavigation() returns null. Can anyone explain why?

Answer №1

We encountered a similar issue after upgrading to Angular 15, but we managed to solve it by implementing a new resolver. This resolver has the ability to access the current route using getCurrentNavigation(), allowing it to send back any "extra" data needed by the component.

@Injectable()
export class MyComponentResolver implements Resolve<MyComponentExtraData> {
  constructor(private router: Router) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): MyComponentExtraData{
  
    return this.router.getCurrentNavigation().extras?.state['MyData'];
  }
}

By utilizing the data returned from the resolver in the component constructor without glitches, you can easily access it through the activatedRoute.snapshot dictionary.

constructor(private activatedRoute: ActivatedRoute) {
 
    let myData = this.activatedRoute.snapshot.data['myData'] /* the myData key depends on how you defined the resolver in your route declaration*/
  }

Answer №2

Starting from Angular version 15, it is possible for

this.router.getCurrentNavigation()
to return null if the component is instantiated after the navigation process.

An alternative approach is to retrieve state information directly from the Location module provided by @angular/common.

import { Location } from '@angular/common';

constructor(private location: Location) {
  location.getState() // utilize the state as needed
}

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 possible to import in TypeScript using only the declaration statement?

Is there a way to use a node module in TypeScript without explicitly importing it after compilation? For example: I have a global variable declared in a file named intellisense.ts where I have: import * as fs from 'fs'; Then in another file, ...

Do Angular pipe promises have the potential to disrupt an application's functionality?

Within my small library, I have implemented a translation pipe that functions perfectly when using Observables. The relevant code snippet can be found here: this.localizationChanges.subscribe(() => { this.fluentService .translationObservable ...

Paginator for Angular Material Cards

This section contains the TypeScript file for a component import { MatTableDataSource, MatPaginator } from "@angular/material"; import { FoodService } from "./food.service"; import { Food } from "./food"; @Component({ selec ...

Are there any @types available for browser extension objects that are interoperable?

I am in the process of developing a browser extension that would work seamlessly on Edge, Chrome, and Firefox by utilizing Typescript. After coming across an article discussing interoperable browser extensions, I stumbled upon a code snippet: window.brow ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

I'm trying to troubleshoot this issue - the duration is showing up as NaN years, NaN months, NaN weeks, NaN days, NaN

Currently I am troubleshooting an issue in my ionic project. I have a button and I want to display the date that the user selects. This is my code: age.component.ts import { Component, OnInit } from '@angular/core'; import * as moment from &apo ...

Angular - Update a single property of the environment

Managing multiple client environments in my Angular application has been a smooth process. Each client has its own set of variables, and by using the configuration flag, I can easily switch between them: { name: client1, address: client 1 address, ... ple ...

Utilizing an Express server instead of Lite server in combination with Angular 2 RC

Looking to develop a single page application using the latest Angular 2 RC and an Express server, but unsure how to connect them without utilizing Bower, Gulp, and Webpack. I have explored some starter packs but haven't found one that meets my expecta ...

Attempting to design an interface in Angular 2 to align with the anticipated API response structure

I have a specific JSON response in mind that I am expecting from an API. My goal is to create a user interface for it. { items: [ { identifier: 1, details: [ { id: 1001, perishable: 0 }, { ...

`What is the best way to transfer an observable to a child component?`

I am facing an issue with passing an Observable down to a child component. I have tried various solutions but none seem to work. parent.component.ts: export class ParentComponent { items$ = of([{name: "Item 1"}, {name: "Item 2"}]); } ...

Disable and grey out the button while waiting for the Observable to broadcast successfully

component.html <button mat-raised-button color="primary" type="submit"> <mat-icon>account_box</mat-icon> <span *ngIf="!loading">&nbsp;&nbsp;&nbsp;Register</span> <span * ...

Building the Android release version of an Ionic Cordova app using the command `ionic cordova build android –prod –release` may encounter a failure when it

Having an issue with Ionic 3. Whenever I use cordova build android --prod --release, the APK shows a white screen after splash. Alternatively, when using ionic cordova build android --prod --release, I encounter the following error. https://i.stack.imgur. ...

Sorting array of arrays in TypeScript and Node.js involves defining the arrays and then applying a sorting algorithm

Recently delved into TypeScript with limited JavaScript knowledge just a couple of weeks ago. I am attempting to scan through all the files in a particular directory, gather each file name (string) and modification time (number>), then organize them in ...

Establish an enumeration using universally recognized identifiers

I have a JavaScript function that requires a numerical input, as well as some predefined constants at the top level: var FOO = 1; var BAR = 2; The function should only be called using one of these constants. To ensure type safety in TypeScript, I am att ...

What could be causing the angular Data table to not display properly?

I am currently exploring Angular Datatables and have a question about re-rendering the datatable after it has been hidden. Can anyone provide guidance on how to achieve this? In my project, I have two components - Parent and Child - that can be hidden or ...

Exploring the implementation of if/else statements in Sass/HTML

I need assistance with customizing the appearance of a save button on my form. The button is currently disabled and appears in blue color, but I would like it to change to a different color until all fields within the form are completed. Even though it c ...

Clarification Needed on Keyup Event in Angular 2

Within my application, I am dynamically adding a class based on certain conditions. When the user inputs something, I validate the value and then add the appropriate class accordingly. This functionality is functioning as expected. However, the class upda ...

Tips for resetting the mat-progress-spinner to its initial state

I want to use the spinner as a timer and switch the progress direction. Currently, it moves clockwise when going from 0 to 100, but I need it to go counterclockwise from 100 (equivalent to 15 minutes or 900 seconds) to 0 (when time runs out). <mat-prog ...

Refreshing manually will display only the JSON data

Utilizing a NodeJS server to fetch information from a MySQL database and presenting it as a JSON object is the task at hand. app.get('/random', (req, res) => { var connection = mysql.createConnection({ host: 'localhost', ...

Managing multiple asynchronous requests through Observables in web development

I am working on an Angular2 website that sends multiple ajax requests using Json Web Tokens for authorization when it is initialized Here are two examples: public getUser(): Observable<User> { // Code block to get user data } public getFriends ...