在最新版本的Angular 7.2.6中,我尝试在路由器本身中传递数据
this.router.navigate(['other'], {state: {someData: 'qwert'}}
Run Code Online (Sandbox Code Playgroud)
在OtherComponent文件中,this.router.getCurrentNavigation()始终返回null
Bat*_*jus 35
您调用该方法getCurrentNavigation为时已晚。导航已完成。
您需要getCurrentNavigation在构造函数内部调用方法:
constructor(private router: Router) {
this.name = this.router.getCurrentNavigation().extras.state.example;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果要访问导航,则ngOnInit可以执行以下操作:
ngOnInit() {
this.name = history.state.example;
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*ler 22
自 Angular 16 起,将lastSuccessfulNavigation替换 v15 中引入的重大更改,其中getCurrentNavigation可能会返回null。
从 Angular 15 开始,this.router.getCurrentNavigation()可能会返回 null,因为组件是在导航后实例化的。
Location另一种方法是从(来自 的那个@angular/common)访问状态
import { Location } from '@angular/common';
constructor(private location: Location) {
location.getState() // do what you want
}
Run Code Online (Sandbox Code Playgroud)
像这样更改代码,因为constructor()只有在ngOnInit()被调用之后,值才会变为空
constructor(private router: Router) {
this.name = this.router.getCurrentNavigation().extras.state.example;
}
Run Code Online (Sandbox Code Playgroud)