无法获取与Aurelia Event Aggregator一起发布的SignalR客户端事件

问题描述:

我有一个基于Aurelia的单页应用程序,我试图让它与现有的SignalR后端一起工作。我已经下载了SignalR javascript客户端并手动将其与Aurelia应用程序集成(即,我没有使用代理文件)。我能够连接到SignalR集线器并查看控制台中的活动消息....迄今为止非常好。现在,我正尝试使用Aurelia Event Aggregator,以便在新的中心消息到达时触发事件,并且该应用程序的任何组件都订阅了该特定事件将会执行一些工作。问题在于SignalR事件回调似乎无法访问Event Aggregator对象。下面的代码来说明问题:在回调函数中引用无法获取与Aurelia Event Aggregator一起发布的SignalR客户端事件

//Import statements omitted for brevity 

@inject (EventAggregator) 
export class MyService{ 

    constructor(eventAggregator) { 

     this.ea = eventAggregator; 

     this.connection = $.hubConnection("http://localhost:8080/signalr", { useDefaultPath: false }); 

     this.hub = this.connection.createHubProxy("myHub"); 

     //Register a callback function to fire when a new hub message arrives   
     this.hub.on("sendMessage", this.processHubMessage); 

     //No issues so far - all this constructor code works fine  
    } 

    processHubMessage(message) { 

     // This doesn't work - this.ea is undefined in the scope of this function 
     this.ea.publish('deviceStatusUpdate', message); 
    } 
} 

事件聚合对象是没有定义 - 我假设,因为它没有被类的范围内调用。有没有办法解决这个问题?我如何给回调函数访问类属性(在本例中为this.ea)。

使用

this.hub.on("sendMessage", (message) => this.processHubMessage(message)); 

它的失败对你由于this怎么不是你希望它是尝试。通过使用胖箭头功能,this是你所期望的。这是JavaScript的一个令人沮丧的部分,但胖箭头为它提供了一个简单的解决方法。

+0

感谢您的帮助...这完美! – CharlieB

我认为你错过了代理的'开始',也可能需要将你的视图模型别名传递给HubProxy。

这个工作对我来说:

constructor(eventAggregator){ 
    this.eventAggregator = eventAggregator; 

    var signalrAddress = 'https://pathToYouServer'; 
    var hubName = 'yourHubsName'; 

    var connection = $.hubConnection(signalrAddress); 
    var eventHubProxy = connection.createHubProxy(hubName); 
    var vm = this; 

    eventHubProxy.on('yourBroadcastMessage', function(data) { 
     vm.eventAggregator.publish(data); 
    }); 

    connection.start(); 
}