AngularJS 和带有 SignalR 的打字稿
AngularJS and Typescript with SingalR
我有以下代码:
控制器:
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" 范围的问题吗?
你认为我做错了什么?
谢谢
您需要执行以下操作:
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
的服务中
我有以下代码:
控制器:
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" 范围的问题吗?
你认为我做错了什么?
谢谢
您需要执行以下操作:
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