如何在ASP.NET Core Angular应用程序中使用SignalR流



我尝试使用SignalR流向客户端发送实时数据,然后在Angular组件的模板上显示数据。

这是我的代码片段,这个函数绑定到模板中的按钮(点击(事件:

getMessage(message: string) {
this.connection = new HubConnectionBuilder().withUrl('/messageHub').build();
const connect = this.connection;
connect.start().then(function () {
connect.stream('SendMessage', message).subscribe({
next: (item) => {
console.log(item);   // <= this works: I can get the data from server
let li = document.createElement("li"); // <= works
li.textContent = item; // <= works
document.getElementById("ulId").appendChild(li); // <= does not work, cannot get dom element by Id....
},
complete: () => {
console.log("finished.");
},
error: (err) => {
console.log(err);
}
});
})
}

我无法工作,如果有人能为我提供一个工作榜样,我将不胜感激。

谢谢,Jack

index.html代码如下:

<div class="container">
<input type="button" id="startStreaming" value="Send" />
<ul id="discussion"></ul>
</div>

.JS代码如下:

var connection = new signalR.HubConnectionBuilder()
.withUrl("/streaming")
.build();
var button = document.getElementById("startStreaming");
function startStreaming(){
connection.stream("StartStreaming").subscribe({
next: onStreamReceived,
err: function(err){
console.log(err);
},
complete: function(){
console.log("finished streaming");
}
});
}
connection.on("streamStarted", function(){
startStreaming();
});
button.addEventListener("click", event => {
connection.invoke("sendStreamInit");
});
function onStreamReceived(data){
console.log("received: " + data);
var liElement = document.createElement('li');
liElement.innerHTML = '<strong>' + "received" + '</strong>:&nbsp;&nbsp;' + data;
document.getElementById('discussion').appendChild(liElement);
}
connection.start();

你可能正在寻找这个:

https://radu-matei.com/blog/signalr-core/#streaming

https://github.com/radu-matei/signalr-samples/blob/master/streaming/web/wwwroot/index.html

将属性添加到类messages: string[];中。更新您的点击事件

getMessage(message: string) {
this.connection = new HubConnectionBuilder().withUrl('/messageHub').build();
const connect = this.connection;
connect.start().then(function () {
connect.stream('SendMessage', message).subscribe({
next: (item) => {
this.messages.push(item);
},
complete: () => {
console.log("finished.");
},
error: (err) => {
console.log(err);
}
});
})

}

现在将你的html设置为类似的内容

<ul class="heroes"> <li *ngFor="let message of messages"> </li> </ul>

现在,对于每个signalR迭代,您的新数据都将被推送到消息数组中,它也将在html中更新。

最新更新