繁体   English   中英

使用 SignalR - Angular 将消息发送到特定浏览器选项卡页面(客户端)

[英]Send Message To Specific Browser Tab Page (Client) using SignalR - Angular

我正在使用这段 Web API C#.Net 核心代码从服务器向客户端发送消息:

public class Test : ITest
{
    private IHubContext<NotificationHub, ITest> _hub;

    public Test(IHubContext<NotificationHub, ITest> hub)
    {
        _hub = hub;
    }

    public async Task BroadcastMessage(string Type, string Payload)
    {
        await _hub.Clients.All.BroadcastMessage(Type, Payload);
    }
}

但它会向所有客户端发送消息,但我只需要将消息发送到正在执行 web API 的打开的标签页(客户端)。 我该怎么做才能做这样的事情?

这是 Angular 代码:

import * as signalR from '@aspnet/signalr';
import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/components/common/messageservice';
import { LogState, ActivityLogType, ContentSearcherResult } from 'src/Model/StartContentSearcher';
import { PropertyRead } from '@angular/compiler';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  constructor(private messageService: MessageService) { }

  private connection: signalR.HubConnection;

  connect(accessToken) {
    if (!this.connection) {
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl("http://localhost:8178/contentsearcherHub", { accessTokenFactory: () => accessToken }).build();

      this.connection.start().catch(err => console.error(err))
      this.connection.on("BroadcastMessage", (Type, Payload) => { console.log(Type, Payload) })
    }
  }

  ngOnInit(): void {
    this.connect("3076a225-f2f6-4c68-b894-08accb62bb90");

  }

  uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

}

我只需要将消息发送到正在执行 web API 的打开的标签页(客户端)。 我该怎么做才能做这样的事情?

客户端启动/建立与中心服务器的连接后,我们可以获得当前连接的客户端的连接 ID。 要仅向使用 API 的特定客户端广播消息,您可以修改连接 ID 并将其传递给 BroadcastMessage 方法,如下所示。

public async Task BroadcastMessage(string connectionId, string Type, string Payload)
{
    await _hub.Clients.Client(connectionId).BroadcastMessage(Type, Payload);
}

我有一个 Angular 项目,我在其中使用 Signalr。 但是当我得到connectionId时,我可以打印它。 但我不能在全局变量中分配它。 这是我的代码:

connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:8178/notifyHub").build();
connection.start().then(function () {
  connection.invoke("GetConnectionId").then(function (connectionId) {
   console.log(connectionId);
   // var temp=connectionId
  })
}).catch(err => console.error(err));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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