当我在 ngOnInit() 中使用 router.getCurrentNavigation() 时,它会给我类型错误,但是当我在构造函数中使用它时,它工作正常,为啥?

Posted

技术标签:

【中文标题】当我在 ngOnInit() 中使用 router.getCurrentNavigation() 时,它会给我类型错误,但是当我在构造函数中使用它时,它工作正常,为啥?【英文标题】:when i use router.getCurrentNavigation() inside ngOnInit() it gives me type error but when i use it inside constructor it works fine, why?当我在 ngOnInit() 中使用 router.getCurrentNavigation() 时,它会给我类型错误,但是当我在构造函数中使用它时,它工作正常,为什么? 【发布时间】:2021-06-19 01:44:20 【问题描述】:

入门-

export class HeaderComponent implements OnInit 

constructor(private route: ActivatedRoute, private router: Router) 

onClick() 
 const navigationExtras: NavigationExtras = 
   state: 
     transd: 'TRANS001',
     workQueue: false,
     services: 10,
     code: '003',
   ,
 ;

  this.router.navigate(['/auth'], navigationExtras);
 

AuthComponent - 在 ngOnInit() 内部使用时:

ngOnInit(): void 

this.authService.authError.subscribe(
  (error) => (this.errorMessage = error)
);

const navigation = this.router.getCurrentNavigation();
const state = navigation.extras.state as 
  transId: string;
  workQueue: boolean;
  services: number;
  code: string;
;

console.dir(state);

在 ngOnInit() 中使用时,它给了我一个错误:

core.js:5980 ERROR TypeError: Cannot read property 'extras' of null
    at AuthComponent.ngOnInit (auth.component.ts:26)
    at callHook (core.js:2486)
    at callHooks (core.js:2457)
    at executeInitAndCheckHooks (core.js:2408)`
    at refreshView (core.js:9207)
    at refreshEmbeddedViews (core.js:10312)
    at refreshView (core.js:9216)
    at refreshComponent (core.js:10358)
    at refreshChildComponents (core.js:8989)
    at refreshView (core.js:9242)

但是当我将它放在构造函数中时它工作正常:

constructor(private authService: AuthService, private router: Router)     
    const navigation = this.router.getCurrentNavigation();
    const state = navigation.extras.state as 
      transId: string;
      workQueue: boolean;
      services: number;
      code: string;
    ;

    console.dir(state);
  

那么,为什么它在构造函数中有效,但在 ngOnInit 中无效?

【问题讨论】:

【参考方案1】:

在 ngOnInit() 中你可以使用历史记录:

ngOnInit() 
  const state = history.state;

必须在构造函数内部调用 getCurrentNavigation(),因为在 ngOnInit() 中导航已经完成。

【讨论】:

以上是关于当我在 ngOnInit() 中使用 router.getCurrentNavigation() 时,它会给我类型错误,但是当我在构造函数中使用它时,它工作正常,为啥?的主要内容,如果未能解决你的问题,请参考以下文章

订阅角度时无法在 ngoninit 中获得价值

在 ngOnInit 中调用多个异步函数的问题

如何重定向到 ngOnInit 中的新组件

ngIf 的组件初始化不会触发 ngOnInit

除了ngOnInit()之外的另一个函数中的空数组[重复]

组件销毁并重新访问后,订阅在 ngOnInit 函数中运行