路由器 getCurrent導航始终返回 null

在最新版本的 Angular 7.2.6中,我试图在路由器中传递数据

this.router.navigate(['other'], {state: {someData: 'qwert'}}

OtherComponent文件中,this.router.getCurrentNavigation()始终返回 null

Stackblitz Link

Angular Docs-getCurrent導航

角度文档状态

43112 次浏览

change the code like this because after constructor() only the ngOnInit() gets called so the value is getting null

constructor(private router: Router) {
this.name = this.router.getCurrentNavigation().extras.state.example;
}

You're calling the method getCurrentNavigation too late. The navigation has finished.

You need call the getCurrentNavigation method inside of the constructor:

constructor(private router: Router) {
this.name = this.router.getCurrentNavigation().extras.state.someData;
}

Or if you want to access the navigation in ngOnInit you can do following:

ngOnInit() {
this.name = history.state.someData;
}

work for me Ionic 4

  • this.router.url => /app/menu/etc // current position

This happened to me because there was a promise (asynchronous process) in the Event of the NavigationEnd, before consuming the getCurrentNavigation().extras().state of the current state.

I moved the promise after and voila! It managed to get the data without first being cleaned.

For spec (tests), the getCurrentNavigation() on constructor don´t work, you have to use the history at ngOnInit() and mock values at history, for example:

beforeEach(() => {
window.history.pushState({name: 'MyName', id: 1}, '', '');
}

Now your component can use this values on ngOnInit() and use on spec.:

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

If your path is registered with a parameter:

{path: 'somePath/:id', component: SomeComponent}

It's important to navigate to it correctly:

this.router.navigate(['/some', id], {state: {data: id}});

Incorrect would be:

this.router.navigate(['/some'+'/'+id], {state: {data: id}});

Angular does not warn you about incorrect usage and this.router.getCurrentNavigation().extras.state is not set.