简体   繁体   English

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

[英]Angular 2 - Cannot access component members/methods from SignalR scope

I am trying to use signalr (externally loaded scripts) with angular 2 components but facing a wired issue. 我正在尝试将Signalr(外部加载的脚本)与angular 2组件一起使用,但面临有线问题。 My functions are getting called in typescript with correct information that I am passing from WebAPI but inside those typescript functions I cannot use any of my declared properties or functions. 我的函数在打字稿中被调用,并带有从WebAPI传递的正确信息,但在这些打字稿函数中,我无法使用任何已声明的属性或函数。

From my WebAPI, I am notifying the clients like 从我的WebAPI,我通知客户

IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<CarBidHub>();
hubContext.Clients.All.NotifyManager_BidPlaced(message);

This initiates a call in my angular component where I have defined it like 这会在我定义它的角度组件中发起呼叫

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();
    }
}

I have tried to call 我试图打电话

//call start hub method 
this.startHub();

from ngAfterViewInit, OnInit and constructor of the component but none worked. 来自ngAfterViewInit,OnInit和组件的构造函数,但均无效。

I can guess the issue that signalr's receiver is defined inside a typescript function so it might not have the right context when called externally. 我可以猜测信号发出者的接收器是在typescript函数中定义的,因此在外部调用时可能没有正确的上下文。

Is there a way I could access declared members from this NotifyManager_BidPlaced function? 有什么方法可以从此NotifyManager_BidPlaced函数访问声明的成员吗?

Lots of examples out there with the same issue. 许多例子都存在相同的问题。 Rule of thumb, never use the function keyword inside your classes. 根据经验,切勿在类内部使用function关键字。 This will replace the this context with that of the current function scope. 这将用当前函数范围的上下文替换this上下文。 Always use the () => {} notation: 始终使用() => {}表示法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM