我正在开发一个 Angular 应用程序,我必须使用 .netcore 服务器和 signalR 将数据从角度形式发送到外部服务器。我可以使用信号集线器在 Angular 客户端和控制器之间建立连接,但我很困惑如何将 json 对象从客户端发送到控制器。我想从控制器将 Json 对象发送到外部服务器。我想使用信号器来实现这一点,因为我希望外部服务器和客户端之间进行实时通信。当我提交数据并收到来自外部服务器的响应时,我想提醒客户端。我正在寻找一些关于如何实现这一点的指导。
角度客户端
_hubConnection: HubConnection;
transportType = signalR.HttpTransportType.LongPolling;
ngOnInit() {
this._hubConnection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Information)
.withUrl("http://localhost:5000/message", this.transportType)
.build();
}
fun1(){
this._hubConnection.on("Send", (user, message) => {
const received = `name: ${user}, message: ${message}`;
console.log(received);
});
this._hubConnection.start()
.then(() =>
this._hubConnection.invoke('Send', "rk", "wassup").catch(function (err) {
console.error(err.toString());
})
)
.then(() =>
console.log('connected')
)
.then(() => this._hubConnection.stop())
.then(() => console.log('Disconnected'))
.catch(e => console.error(e.message));
控制器
namespace ang.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DistController : Controller
{
private IHubContext<DistHub> _hubContext;
public DistController(IHubContext<DistHub> hubContext)
{
_hubContext = hubContext;
}
}
}
SignalR 集线器
namespace ang.HubConfig
{
public class DistHub: Hub
{
public async Task Send (string user , string message)
{
// return Clients.All.SendAsync("Send", message);
await Clients.All.SendAsync("Send", user, message);
}
}
}
启动.cs
app.UseSignalR(routes =>
{
routes.MapHub<DistHub>("/message");
});
json对象
const Root = {
"Unit" : "mm",
"test": [{
"Val": this.Val1.isChecked,
'Val1' : this.val2.isChecked,
}],
"test1" :{
"sub":[{
'val2' : this.valFormGroup.get('val2').value,
'Val3' : this.valFormGroup.get('val3').value,
}]
},
}