Search code examples
javascriptangularjstypescriptsignalrsignalr-hub

AngularJS and Typescript with SingalR


I have the following code:

Controller:

class MyController {
    private names: string[];
    private myHub:any;
    constructor(){

        this.myHub = $.connection.myHub;
        this.myHub.client.clientMethod = (name:string) =>{
            // "name" gets added to the this.names array but does not get displayed in the view.
            this.names.push(name);
        });
        $.connection.hub.start().done(()=>{
            this.myHub.server.myServerMethod();
        });

        // "test name" gets added to the this.name array and is viewed in the view
        this.names.push("test name");

    }

}

View:

<div ng-controller="MyController as c">
    <ul>
        <li ng-repeat="n in c.names">{{n}}</li>
    </ul>
</div>

The code in the controller works fine. The SignalR Hub is doing exactly what it's supposed to do. The "clientMethod" gets called from the server and the "this.names.push(name)" gets executed as expected and pushes the name into the array. But for some reason the names do not get displayed in the View. If I physically push a string into the this.names array it gets displayed without a problem.

Could this be a problem with the "this" scope of the controller?

What do you think I'm doing wrong?

Thanks


Solution

  • You need to do the following:

      this.myHub.client.clientMethod = (name:string) =>{
                // "name" gets added to the this.names array but does not get displayed in the view.
                this.names.push(name);
            });
    

    In the context of a $scope.$apply():

      this.myHub.client.clientMethod = (name:string) =>{
                scope.$apply(()=>{
                    this.names.push(name);
                });
            });
    

    Ofcourse this means you need to take scope in as a constructor parameter.

    Alternatively you can wrap all the signalr stuff into a service that uses $rootScope