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

Problem displaying images in Mean stack app using CSS background-image and Webpack

Currently, I am enhancing my skills by working on my own projects. One of the projects I'm focused on right now is designing a MEAN-stack app that utilizes Webpack. In the past, I encountered an issue where I couldn't display images in my app. Ho ...

Refresh the information in the <ion-datetime> component by utilizing the formGroup

I am currently working with a form that has been created using 'FormBuilder'. The form includes a date control and I am trying to figure out how to update the data in that control using the patchValue() method. In the template, the control has d ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

Discovering various kinds of data with a single generic type

I am looking to define a specific type like this: type RenderItems<T> = { [K in keyof T]: { label: string; options: { defaultValue: T[K]['options'][current_index_of_array]; item: (value: T[K][&apo ...

What strategies should be employed to develop an Angular 4 application seamlessly integrated with Asp.NET Core?

I attempted to test out a couple of templates which turned out to be unsuccessful: https://github.com/asadsahi/AspNetCoreSpa https://github.com/MarkPieszak/aspnetcore-angular2-universal Unfortunately, neither of them worked properly for me. I'm cu ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

How can you utilize a JavaScript library that provides global variables in Typescript?

I am closely adhering to the guidance provided in the official manual for declaration. Global library // example.js example = 20; Declaration file // example.d.ts declare const let example: number; Implementing the declaration file and library // ind ...

What is the process for incorporating the jsnetworkx library into an ionic or angular 4 project?

When using any Ionic3 app service import * as jsnx from 'jsnetworkx'; The output error message is: Uncaught (in promise): Error: Cannot find module "lodash/lang/isPlainObject" Error: Cannot find module "lodash/lang/isPlainObject" at webpackMis ...

Ways to check my component using ActivatedRoute?

I am currently facing an issue while testing a component that utilizes two resolvers (pagesResolver and UploadResolver): Below is the code snippet for my component: export class AdminPagesComponent implements OnInit { fileUploads$: Observable<FileUpl ...

Sharing data between components in Angular 2 using the <router-outlet> technique

Having just started exploring Angular 2, I am eager to pass a boolean value from one component to another using <router-outlet> After some research, it seems like the best approach is to utilize a service. My aim is to toggle a boolean variable in ...

Loading dynamic content within Angular Material tabs allows for a more customized and interactive user experience

I am currently working on creating a dynamic tab system using Angular Material: Tabs. I have encountered an issue with loading content on tabs after the initial one, where the functionality only works when the first tab is loaded. Below you can see the ta ...

Update the response type for http.post function

I've implemented a post method using Angular's HttpClient. While attempting to subscribe to the response for additional tasks, I encountered the following error: Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{}, ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...

Utilizing ngFor in Angular to dynamically refer to named variables within ngIf

I am looking to access the input element within the ngIf directive in order to check if it currently contains a specific value. The issue lies with the code inside the ngIf statement. <span *ngFor="let item of items;let i=index"> <input t ...

Sending data to Dialog Component

While working on implementing the dialog component of material2, I encountered a particular issue: I am aiming to create a versatile dialog for all confirmation messages, allowing developers to input text based on business requirements. However, according ...

Implementing Angular Universal on Azure Platform

After converting my application to Angular Universal at the request of my clients, I successfully ran it using npm run serve:ssr and accessed it through http://localhost:4000. Now, the challenge lies in deploying it. Upon running npm run build:ssr, a dist ...

Encountered an error while trying to install a package using NPM due to the requirement of 'require-from-string@

Every time I try to install a package (even nodejs), I encounter this issue. Here is what I have tried so far: Uninstalled all dependencies Cleared cache Reinstalled NPM / AngularCli Unfortunately, running any NPM command still results in the same error ...

Struggling with Angular 5 Facebook authentication and attempting to successfully navigate to the main landing page

I have been working on integrating a register with Facebook feature into an Angular 5 application. Utilizing the Facebook SDK for JavaScript has presented a challenge due to the asynchronous nature of the authentication methods, making it difficult to redi ...

Is it possible to define TypeScript interfaces in a separate file and utilize them without the need for importing?

Currently, I find myself either declaring interfaces directly where I use them or importing them like import {ISomeInterface} from './somePlace'. Is there a way to centralize interface declarations in files like something.interface.ts and use the ...

How come a Google Maps API component functions properly even without using *NgIf, but fails to work when excluded in Angular 9?

I recently followed the guide provided in this discussion with success. The method outlined worked perfectly for loading search boxes using this component: map.component.html <input id= 'box2' *ngIf="boxReady" class="controls" type="text" p ...