【问题标题】:Router getCurrentNavigation always returns null路由器 getCurrentNavigation 始终返回 null
【发布时间】:2019-07-20 07:51:09
【问题描述】:

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

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

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

Stackblitz Link

Angular Docs - getCurrentNavigation

Angular Docs - state

【问题讨论】:

标签: angular


【解决方案1】:

你调用getCurrentNavigation 方法太晚了。导航完成。

您需要在构造函数内部调用getCurrentNavigation 方法:

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

或者,如果您想访问ngOnInit 中的导航,您可以执行以下操作:

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

【讨论】:

  • @Carlos.V 不,它没有! :\
  • 工作完美.. :) 谢谢
  • 当导航来自 app.component 中的 InitializeApp 时,这对我不起作用
  • 就我而言,我在ngOnInit 中使用它,但在等待另一种方法完成后,因此它评估为空。在 ngOnInit 方法中独立触发时按预期工作!
【解决方案2】:

对于规范(测试),constructor 上的 getCurrentNavigation() 不起作用,您必须使用 ngOnInit() 上的 historyhistory 上的模拟值,例如:

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

现在您的组件可以在 ngOnInit() 上使用此值并在规范上使用:

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

【讨论】:

    【解决方案3】:

    这发生在我身上是因为在使用当前状态的 getCurrentNavigation().extras().state 之前,在 NavigationEnd 的 Event 中有一个 promise(异步过程)。

    我移动了承诺,瞧!它设法在没有先被清理的情况下获取数据。

    【讨论】:

      【解决方案4】:

      为我工作 Ionic 4

      • this.router.url => /app/menu/etc // 当前位置

      【讨论】:

        【解决方案5】:

        像这样更改代码,因为在 constructor() 之后,只有 ngOnInit() 被调用,因此值变为空

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

        【讨论】:

          猜你喜欢
          • 2016-05-31
          • 2015-08-15
          • 2012-03-18
          • 2016-11-04
          • 2016-07-28
          • 2010-11-08
          • 2017-11-26
          • 2015-02-23
          • 2017-11-16
          相关资源
          最近更新 更多