【问题标题】:How to get notification only for few items from signalR? (EF core and Angular 8)如何仅从 signalR 获取少数项目的通知? (EF 核心和 Angular 8)
【发布时间】:2020-03-12 15:58:27
【问题描述】:

在我们的 .Net 核心和 Angular 8 应用程序中,我们实现了 SignalR。我们需要关于不同事件的实时通知。

事件(在我们的应用程序中)是一个动态创建的项目。 (生日活动、周年纪念活动等)

假设用户可以打开任何活动。很少有民意调查和聊天正在进行中。每当用户更改事件中的某些内容时,我需要通知打开相同事件的其他客户。

目前,来自所有事件的通知都会发送到所有客户端(无论他们打开了哪些事件)

public class NotificationHub : Hub    {
    public async Task UpdateVote(int eventId, int pollId, int pollOptionId)
    {
        await Clients.Others.SendAsync("VoteUpdated", eventId, pollId, pollOptionId);
    }
}

角度:

private CreateConnection() {
    this._hubConnection = new HubConnectionBuilder()
      .withUrl(environment.base + 'NotificationHub')
      .build();
  }

  private StartConnection(): void {
    this._hubConnection
      .start()
      .then(() => {
        this.connectionIsEstablished = true;
        console.log('Hub connection started');
        this.connectionEstablished.emit(true);
      })
      .catch(err => {
        console.log('Error while establishing connection, retrying...');
        setTimeout(function () { this.StartConnection(); }, 5000);
      });
  }

UpdateVote(eventId, pollId, pollOptionId) {
    this._hubConnection.invoke('UpdateVote', eventId, pollId, pollOptionId);
  }

private RegisterOnServerEvents(): void {
    this._hubConnection.on('VoteUpdated', (eventId, pollId, pollOptionId) => {
      this.VoteUpdated.emit({ eventId, pollId, pollOptionId });
    });
  }

我在加载网站时打开连接。

我需要执行什么操作才能只通知客户他们已打开的事件?

【问题讨论】:

  • 将它们添加到组中。就像每当用户访问一个事件时,将他们添加到像"Event-" + eventId 这样的组中,并且当发生更改时仅通知该组。当他们关闭该页面时,请记住从组中删除
  • @NoobCoder 我建议你添加一个答案,因为这是正确的方法
  • @alessandro 添加了答案。

标签: angular asp.net-core signalr


【解决方案1】:

将它们添加到组中。就像每当用户访问事件时,将他们添加到“Event-”+ eventId 之类的组中,并且在发生更改时仅通知该组。当他们关闭该页面时,请记住从组中删除

public async AddToTrackGroup(string eventId) {
        return Groups.Add(Context.ConnectionId, "event-" + eventId);
}

public async Task UpdateEventViewer(string eventId)
{
    Clients.Group("event-" + eventId).notifyEventChanged();
}

【讨论】:

  • 谢谢。它工作得很好!出于某种原因,它显示“AddToGroupAsync”和“RemoveFromGroupAsync”作为功能。可能版本不一样。但我明白了。现在我只使用“Clients.OthersInGroup”通知目标客户。
  • 是的,这只是一个伪代码。我很高兴它为你工作
猜你喜欢
  • 2020-03-22
  • 2019-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
相关资源
最近更新 更多