我尝试设置一个简单的错误通知组件,在Visual Studio中进行调试时,在订阅中,此似乎未定义。
public notifications: NotificationMessage[];
constructor(notificationService: NotificationService) {
this.notifications = []; //'this' is defined here
notificationService.rxEmitter.subscribe((notificationMessages: any) => {
this.notifications = notificationMessages; //'this' is undefined here
});
}
编辑:Screenshot这是从VS中的断点未定义的。有趣的是,' _this' 在运行时存在,但我不能引用它,因为typescript会在编译时抛出引用未找到的错误。
答案 0 :(得分:0)
事实证明Visual Studios调试器给了我一个红鲱鱼说这是未定义的。使用console.log测试它会产生有效的输出。
Visual Studio在箭头功能方面遇到问题。打字稿将此编译为 _this 。
如果您在subscribe中创建断点并检查 this ,Visual Studios调试器将检查上面生成的javascript代码中的匿名函数,并且无法再找到此
解决方法是检查 _this 。
这篇文章似乎描述了我的问题。