RxJS: Why is 'this' undefined within subscribe [closed]

陌路散爱 提交于 2019-12-11 06:36:42

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/45566506/rxjs-why-is-this-undefined-within-subscribe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!