RxJS:为什么在订阅中未定义"this" [英] RxJS: Why is 'this' undefined within subscribe

查看:71
本文介绍了RxJS:为什么在订阅中未定义"this"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个简单的错误通知组件,而在Visual Studio中在订阅中进行调试时,似乎未定义.

 公共通知:NotificationMessage [];构造函数(notificationService:NotificationService){this.notifications = [];//'this'在这里定义notificationService.rxEmitter.subscribe((notificationMessages:any)=> {this.notifications = notificationMessages;//'this'在这里未定义});} 

如果您在subscribe中创建一个断点并检查,Visual Studios调试器将检查上面生成的javascript代码中的匿名函数,并且将不再找到

一种解决方法是改为检查 _this .

本文似乎描述了我的问题.

https://typescript.codeplex.com/workitem/1655

I'm trying to setup a simple error notifications component, whilst debugging in Visual Studio, within subscribe, this appears to be undefined.

public notifications: NotificationMessage[]; 

constructor(notificationService: NotificationService) {
    this.notifications = []; //'this' is defined here

    notificationService.rxEmitter.subscribe((notificationMessages: any) => {
        this.notifications = notificationMessages; //'this' is undefined here
    });
}

Edit : Screenshot of this being undefined from a breakpoint in VS. Interestingly, '_this', does exist at runtime, though I can't reference it as typescript throws an reference not found error on compilation.

解决方案

It turns out Visual Studios debugger was giving me a red herring saying this is undefined. Testing it out with console.log gave a valid output.

Visual Studio has trouble with arrow functions. Typescript compiles this to _this.

If you create a breakpoint from within subscribe and inspect this, Visual Studios debugger will be inspecting the anonymous function in the generated javascript code above and can no longer find this.

A workaround is to inspect _this instead.

This article seems to describe my issue.

https://typescript.codeplex.com/workitem/1655

这篇关于RxJS:为什么在订阅中未定义"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆