【问题标题】:Angular 2 - Cannot access component members/methods from SignalR scopeAngular 2 - 无法从 SignalR 范围访问组件成员/方法
【发布时间】:2017-01-24 19:18:53
【问题描述】:

我正在尝试将信号器(外部加载的脚本)与 angular 2 组件一起使用,但面临有线问题。我的函数在 typescript 中被调用,其中包含我从 WebAPI 传递的正确信息,但在这些 typescript 函数中,我无法使用我声明的任何属性或函数。

通过我的 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 函数?

【问题讨论】:

    标签: javascript angular typescript signalr signalr-hub


    【解决方案1】:

    有很多相同问题的示例。经验法则,永远不要在你的类中使用function 关键字。这会将this 上下文替换为当前函数范围的上下文。始终使用() =&gt; {} 表示法:

    private startHub(): void {
        jQuery.connection.hub.logging = false;
    
        hub.client.NotifyManager_BidPlaced = (message:string) => { //here
          this.notificationService.success('Information', message);   
        };
    
        jQuery.connection.hub.start();
    }
    

    【讨论】:

    • 工作就像一个魅力!我从来不知道它通过使用 function 关键字来改变范围,谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2018-06-20
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多