在Angular中,getCurrentNavigation()方法用于获取当前路由的导航状态。然而,在某些情况下,该方法可能返回null值,这可能是由于异步导航或刷新页面等原因造成的。以下是解决此问题的一种常见方法:
import { Router, NavigationEnd } from '@angular/router';
export class YourComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const navigation = this.router.getCurrentNavigation();
if (navigation) {
const data = navigation.extras.state;
// 使用获取到的data进行后续操作
}
}
});
}
}
在上面的代码中,我们订阅了路由事件,并在每次导航结束时检查getCurrentNavigation()方法的返回值。如果返回值不为null,我们可以从导航对象的extras属性中获取数据。
import { Router, ActivatedRoute } from '@angular/router';
export class YourComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute) {}
ngOnInit() {
const navigation = this.router.getCurrentNavigation();
const data = navigation?.extras?.state;
// 使用获取到的data进行后续操作
}
}
在上面的代码中,我们通过注入ActivatedRoute来获取当前路由的导航信息。然后,我们可以使用getCurrentNavigation()方法来获取数据。
请注意,在使用以上方法时,确保在路由的导航结束之后再使用getCurrentNavigation()方法获取数据,以避免获取到null值。