【发布时间】:2020-02-04 18:47:51
【问题描述】:
我正在使用这段 Web API C# .Net Core 代码从服务器向客户端发送消息:
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);
});
}
}
【问题讨论】:
标签: c# signalr angular7 asp.net-core-webapi