我有一个在我的组件的不同位置调用的方法,如下所示:
this.updateResults();
此方法依赖于组件上的几个属性。该方法在从模板调用的方法中运行良好,但我希望它在queryParams更改后工作,因此我使用以下代码:
ngOnInit() { this.navigationSubscription = this._router.events.subscribe((e: any) => { if (e instanceof NavigationEnd) { this.updateResults(); } }); }
该方法在预期的时间执行,但我可以在调试器中看到,当它执行时,所需的属性为null。
_this 而不是 this this.propertyName 我想这不管用。
_this
this
this.propertyName
您可以尝试以下方法:
ngOnInit() { const _this = this; this.navigationSubscription = this._router.events.subscribe((e: any) => { if (e instanceof NavigationEnd) { _this.updateResults(); } }); }
我不确定在您的案例中,范围是否真的是一个问题,但这种方法有时已经救了我。