Javascript 带信号的AngularJS和Typescript

Javascript 带信号的AngularJS和Typescript,javascript,angularjs,typescript,signalr,signalr-hub,Javascript,Angularjs,Typescript,Signalr,Signalr Hub,我有以下代码: 控制器: class MyController { private names: string[]; private myHub:any; constructor(){ this.myHub = $.connection.myHub; this.myHub.client.clientMethod = (name:string) =>{ // "name" gets added to the t

我有以下代码:

控制器:

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");

    }

}
视图:


  • {{n}
控制器中的代码工作正常。信号中心正在做它应该做的事情。从服务器调用“clientMethod”并按预期执行“this.names.push(name)”并将名称推送到数组中。但由于某些原因,这些名称不会显示在视图中。如果我将一个字符串实际推入this.names数组,它将毫无问题地显示出来

这可能是控制器“this”范围的问题吗

你认为我做错了什么


谢谢

您需要执行以下操作:

  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);
        });
$scope.$apply()
的上下文中:

当然,这意味着您需要将
范围
作为构造函数参数


或者,您可以将所有信号器内容包装到一个使用
$rootScope

您需要范围的服务中。$apply()在clientMethod内部,因为它在angular上下文之外运行“这可能是控制器的“this”范围的问题吗?”没有问题。您是否尝试记录此的值?我真的希望人们在进入Typescript之前先学习JS。我的控制器中没有使用“范围”。我使用的是Angular docs@StefanBaiu推荐的“MyController as c”,你必须要求学习mate,冷静点down@StefanBaiuOP使用的是
这个
(这将是词法的
这个
)不是问题,但摘要周期是问题。是的,我最终在我的信号器服务中添加了$rootScope
  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);
        });
  this.myHub.client.clientMethod = (name:string) =>{
            scope.$apply(()=>{
                this.names.push(name);
            });
        });