首页 文章

无法使用Aurelia Event Aggregator发布SignalR客户端事件

提问于
浏览
1

我有一个基于Aurelia的单页应用程序,我正在尝试使用现有的SignalR后端 . 我已经下载了SignalR javascript客户端并手动将其与Aurelia应用程序集成(即我没有使用代理文件) . 我能够连接到SignalR集线器,并在控制台中查看arrvive消息....到目前为止一切顺利 . 现在,我正在尝试使用Aurelia事件聚合器,以便在新的集线器消息到达时触发事件,并且应用订阅该特定事件的任何组件将执行一些工作 . 问题是SignalR事件回调似乎无法访问Event Aggregator对象 . 这是用于说明问题的代码:

//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) .

2 回答

  • 3

    我认为您缺少代理的“开始”,也可能需要为视图模型添加别名以传递给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();
    }
    
  • 0

    尝试使用

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

    由于 this 并不期待它,所以它失败了 . 通过使用胖箭头功能, this 就是您所期望的 . 这是JavaScript的一个非常令人沮丧的部分,但胖箭为它提供了一个简单的解决方法 .

相关问题