如何使用Signalr以角度读取从Web API发送的数据? [英] How to read data sent from web api using signalr in angular?
本文介绍了如何使用Signalr以角度读取从Web API发送的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读取通过角度客户端中的Signalr从asp.net Web API发送的数据.
I want to read data sent from asp.net web api through signalr in angular client.
为此,我在下面给出的Web api上创建了Hub:
For that, I created the Hub at my web api given below :
//ProgressHub.cs
public class ProgressHub : Hub
{
public Task Send(string data)
{
return Clients.All.SendAsync("Send", data);
}
public async Task<string> GetServerTime(IProgress<int> prog)
{
await Task.Run(() => {
for (int i = 0; i < 10; i++)
{
prog.Report(i * 10);
// Call to your client side method.
Clients.Client(Context.ConnectionId).progress(i);
System.Threading.Thread.Sleep(200);
}
});
return DateTime.Now.ToString()+" Test";
}
}
//startup.cs
app.MapSignalR();
在角度客户端中,
private proxy: any;
private proxyName: string = 'progressHub';
private connection: any;
constructor(){
// create hub connection
this.connection = $.hubConnection("http://localhost:53642/");
// create new proxy as name already given in top
this.proxy = this.connection.createHubProxy(this.proxyName);
// call the connecion start method to start the connection to send and receive events.
this.startConnection();
this.proxy.on('Send', (data: any) => {
const received = `Received: ${data}`;
alert(received); //here i want to get the data
});
}
startConnection(): void {
this.connection.start().done((data: any) => {
console.log('Now connected ' + data.transport.name + ', connection ID= ' + data.id);
this.proxy.invoke('GetServerTime', serverMessage =>
{
console.log(serverMessage)
});
}).fail((error: any) => {
console.log('Could not connect ' + error);
});
}
当我运行调试应用程序时,客户端成功连接到Signalr 控制台输出:
when I run debug application , client successfully get connected to signalr console output:
Now connected webSockets, connection ID= 19156d89-d82c-46f9-a109-d8a4828f8ea9
但不返回任何我要提醒的数据.
but doesn't return any data that I want to be alert .
推荐答案
仅适用于asp.net核心
Only for asp.net core
使用 @ aspnet/signalr 包与SignalR一起使用
Use @aspnet/signalr package to work with SignalR
示例 私人枢纽;
Example private hub;
this.hub = new HubConnectionBuilder()
.withUrl("/signalr")
.configureLogging(LogLevel.Error)
.build();
this.hub.start().catch(err => console.error(err.toString()));
然后从服务器发送监听事件
Then listen in event send from server
this.hub.on("Send", (data) =>
console.log(data);
);
更新
public class HomeController : Controller
{
private readonly IHubContext<NotificationHub> _hubContext;
public HomeController(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
}
public async Task<IActionResult> Index()
{
await _hubContext.Clients.All.SendAsync("Notify", $"Home page loaded at: {DateTime.Now}");
return View();
}
您可以在此处查看>
这篇关于如何使用Signalr以角度读取从Web API发送的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文