aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

@aspnet/[email protected] hubConnection.on with `this` points to HubConnection

Open kilanny opened this issue 7 years ago • 2 comments

Describe the bug

For example:

export class SignalRService {

  constructor(
    @Inject('BASE_URL') private baseUrl: string
  ) {
  }

  startConnection(): Promise<void> {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl(`${this.baseUrl}notification`)
      .build();

    return this.hubConnection.start()
      .then(() => {
        console.log('Connection started');
        this.hubConnection.on("onEvt", this.onEvt);
      })
      .catch(err => console.log('Error while starting connection: ' + err));
  }

  private onEvt(json: string) {
   console.log(this); // prints HubConnection !!
  }
}

To Reproduce

Steps to reproduce the behavior:

  1. Using this version of ASP.NET Core 2.2
  2. Run this code (angular 7.2.7)

Expected behavior

this should point to object of type SignalRService but HubConnection is received

kilanny avatar Mar 07 '19 14:03 kilanny

This is expected behavior because of how this works in JavaScript. It's entirely controlled by the caller of the function instead of being defined by where the function is defined (like in C# or other languages). See the documentation on this on Mozilla Developer Network for more detail.

Since HubConnection is calling your function, it ends up being assigned as this by default. This is how JavaScript works, and it is unfortunately quite different from other languages that use this. You can an arrow function to force a specific value for this. My suggestion would be to change the following code:

       this.hubConnection.on("onEvt", this.onEvt);

To something like this:

       this.hubConnection.on("onEvt", (json) => this.onEvt(json));

It looks the same but because you are using an arrow function (() => syntax) the this value inside your arrow function is guaranteed to be the same as the this value outside the function (i.e. the SignalRService instance), so the call should succeed.

analogrelay avatar Mar 07 '19 18:03 analogrelay

Thank you for contacting us. Due to a lack of activity on this discussion issue we're closing it in an effort to keep our backlog clean. If you believe there is a concern related to the ASP.NET Core framework, which hasn't been addressed yet, please file a new issue.

This issue will be locked after 30 more days of inactivity. If you still wish to discuss this subject after then, please create a new issue!

ghost avatar Nov 12 '20 08:11 ghost