Damien Doumer
Damien Doumer

Reputation: 2266

angular when I subscribe to method calls on client side with signalr, the properties of the object containing the hub connection are undefined

When I subscribe to signalr method calls, the properties of the object containing the hub connection are always undefined. I'm using signalr client in an angular app. Please check the comments in my code

// subscribe to a hub connection
this._hubConnection.on("senderDisconnected", this.senderDisconnected);

//The method of the client who subscribed to the hub
private async senderDisconnected(){
    debugger;
    if (this._disconnectedHandler != null){
        //WHen I stop the debugger here, the value of "_disconnectedHandler" is undefined
        //And the value of this is HubConnection. 
        this._disconnectedHandler();
    }
}

My problem is that I can't call _disconnectedHandler() its value is always undefined. when I set a breakpoint I also see the value of "this" is HubConnection instead of being my signalr client which contains the hubconnection.

I'm using angular.

"_disconnectedHandler" is a function passed to my signalr client by the class containing it, so that it calls this function when the disconnected event fires.

Upvotes: 0

Views: 373

Answers (1)

Denis RUNGET
Denis RUNGET

Reputation: 13

Use the Function.prototype.bind

// add this line
this.senderDisconnected = this.senderDisconnected.bind(this);
this._hubConnection.on("senderDisconnected", this.senderDisconnected);

//The method of the client who subscribed to the hub
private async senderDisconnected(){
    this._disconnectedHandler();
}

Upvotes: 0

Related Questions