Angular 9 'this' 在路由器 Navigationend subscribe at debug breakpoint 中未定义
Angular 9 'this' is underfined in router Navigation End subscribe at debug breakpoint
我是 Angular 的新手,仍在学习中。
我有一个订阅路由器 NavigationEnd 事件的组件,该事件访问在从服务解析的路由中初始化的一些变量。
constructor(private route: ActivatedRoute, private router: Router) {
var that = this;
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.nominatim);
}
});}
当我调试代码时,this.nominatim 变量未定义,但它确实包含一个我可以记录到控制台的值。
我在 Whosebug 上发现了另一个问题,它解释了类似的情况
通过添加
var that = this;
在路由器事件订阅之前,我可以在调试中看到变量。
如果我仍然可以使用 'this' 上下文,我会更喜欢它。
我怎样才能让它工作?
首先你不应该在构造函数中订阅。 Angular 文档建议所有工作(除了非常轻的变量赋值)都在 ngOnInit 中完成——为了安全起见,除了依赖注入之外,你不应该使用构造函数。
如果将代码移至 ngOnInit,您可能会发现“this”有效。 ngOnInit 是一个 Angular 生命周期钩子,在构造函数之后很快就会被自动调用。
否则,您可以像这样在 ngOnInit 中调用一个方法:
ngOnInit() {
this.myCodeToSubscribeToRouterEvents()
}
private myCodeToSubscribeToRouterEvents() {
// TODO: Paste your subscription code here
}
然后在构造函数中可以这样写:
constructor(private route: ActivatedRoute, private router: Router) {
this.myCodeToSubscribeToRouterEvents = this.myCodeToSubscribeToRouterEvents.bind(this);
}
是的,我知道我在构造函数中放入了代码,但我只是说不要,但这是罕见的例外之一。此构造函数代码确保在 myCodeToSubscribeToRouterEvents 中“this”始终是组件的实例(这是您想要的)而不是其他东西。
希望对您有所帮助。 J.E.S.U.S爱你:D
关于:
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.nominatim);
你会更好:
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.route.snapshot.data);
这样您就可以检查数据是否通过了:)
我是 Angular 的新手,仍在学习中。
我有一个订阅路由器 NavigationEnd 事件的组件,该事件访问在从服务解析的路由中初始化的一些变量。
constructor(private route: ActivatedRoute, private router: Router) {
var that = this;
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.nominatim);
}
});}
当我调试代码时,this.nominatim 变量未定义,但它确实包含一个我可以记录到控制台的值。
我在 Whosebug 上发现了另一个问题,它解释了类似的情况
通过添加
var that = this;
在路由器事件订阅之前,我可以在调试中看到变量。
如果我仍然可以使用 'this' 上下文,我会更喜欢它。
我怎样才能让它工作?
首先你不应该在构造函数中订阅。 Angular 文档建议所有工作(除了非常轻的变量赋值)都在 ngOnInit 中完成——为了安全起见,除了依赖注入之外,你不应该使用构造函数。
如果将代码移至 ngOnInit,您可能会发现“this”有效。 ngOnInit 是一个 Angular 生命周期钩子,在构造函数之后很快就会被自动调用。
否则,您可以像这样在 ngOnInit 中调用一个方法:
ngOnInit() {
this.myCodeToSubscribeToRouterEvents()
}
private myCodeToSubscribeToRouterEvents() {
// TODO: Paste your subscription code here
}
然后在构造函数中可以这样写:
constructor(private route: ActivatedRoute, private router: Router) {
this.myCodeToSubscribeToRouterEvents = this.myCodeToSubscribeToRouterEvents.bind(this);
}
是的,我知道我在构造函数中放入了代码,但我只是说不要,但这是罕见的例外之一。此构造函数代码确保在 myCodeToSubscribeToRouterEvents 中“this”始终是组件的实例(这是您想要的)而不是其他东西。
希望对您有所帮助。 J.E.S.U.S爱你:D
关于:
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.nominatim);
你会更好:
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.route.snapshot.data);
这样您就可以检查数据是否通过了:)