我有以下代码:
控制器:
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");
}
}
查看:
<div ng-controller="MyController as c">
<ul>
<li ng-repeat="n in c.names">{{n}}</li>
</ul>
</div>
控制器中的代码工作正常。 SignalR Hub正在做它应该做的事情。从服务器调用“clientMethod”并按预期执行“this.names.push(name)”并将名称推送到数组中。但由于某种原因,名称不会显示在视图中。如果我将字符串物理地推入this.names数组,它将显示没有问题。
这可能是控制器“this”范围的问题吗?
你觉得我做错了什么?
由于
答案 0 :(得分:0)
您需要执行以下操作:
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()
:
this.myHub.client.clientMethod = (name:string) =>{
scope.$apply(()=>{
this.names.push(name);
});
});
当然,这意味着您需要将scope
作为构造函数参数。
或者,您可以将所有信号器内容包装到使用$rootScope