[英]Angular 2 - Cannot access component members/methods from SignalR scope
我正在尝试将Signalr(外部加载的脚本)与angular 2组件一起使用,但面临有线问题。 我的函数在打字稿中被调用,并带有从WebAPI传递的正确信息,但在这些打字稿函数中,我无法使用任何已声明的属性或函数。
从我的WebAPI,我通知客户
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<CarBidHub>();
hubContext.Clients.All.NotifyManager_BidPlaced(message);
这会在我定义它的角度组件中发起呼叫
declare var jQuery: any;
declare var moment: any;
var hub = jQuery.connection.carBidHub; //declaring hub
@Component({
selector: 'live-auction',
templateUrl: '/auctions/live/live-auction.html'
})
export class LiveAuctionComponent
{
...
constructor(private notificationService: NotificationsService)
{
}
...
private startHub(): void {
jQuery.connection.hub.logging = false;
hub.client.NotifyManager_BidPlaced = function (message:string) {
//this message is printed on all connected clients
console.log(message);
//but this line below throws an error on all members I am trying to access with "this."
this.notificationService.success('Information', message);
}
//this.notificationService is available here
//Start the hub
jQuery.connection.hub.start();
}
}
我试图打电话
//call start hub method
this.startHub();
来自ngAfterViewInit,OnInit和组件的构造函数,但均无效。
我可以猜测信号发出者的接收器是在typescript函数中定义的,因此在外部调用时可能没有正确的上下文。
有什么方法可以从此NotifyManager_BidPlaced函数访问声明的成员吗?
许多例子都存在相同的问题。 根据经验,切勿在类内部使用function
关键字。 这将用当前函数范围的上下文替换this
上下文。 始终使用() => {}
表示法:
private startHub(): void {
jQuery.connection.hub.logging = false;
hub.client.NotifyManager_BidPlaced = (message:string) => { //here
this.notificationService.success('Information', message);
};
jQuery.connection.hub.start();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.