RxJS: Why is 'this' undefined within subsc

2019-08-03 03:05发布

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条回答
SAY GOODBYE
2楼-- · 2019-08-03 03:26

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.

compiled js of NotifierComponent

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

查看更多
登录 后发表回答