在Angular 9中,可能会遇到在Router Navigation End订阅器中设置调试断点时'this'未定义的问题。这通常是因为在订阅器中使用了箭头函数而不是普通函数,导致'this'的作用域错误。为了解决这个问题,您可以使用普通函数或将该箭头函数转换为普通函数并将'this'作为参数传递。例如:
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe(function(event) { //使用普通函数
if (event instanceof NavigationEnd) {
// Your code here
}
});
}
}
或
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe((event) => this.handleNavigationEnd(event)); //使用箭头函数
}
handleNavigationEnd(event: any) {
if (event instanceof NavigationEnd) {
// Your code here
}
}
}
通过使用普通函数或将箭头函数转换为普通函数并将'this'作为参数传递,您可以避免'this'未定义的问题,并在订阅器中设置调试断点。