角度 2 - 无法从 SignalR 范围访问组件成员/方法



我正在尝试使用带有角度 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和组件的构造函数,但没有一个工作。

我可以猜到信号器的接收器是在打字稿函数中定义的问题,因此在外部调用时它可能没有正确的上下文。

有没有办法从这里访问声明的成员 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();
}

最新更新