3

I am developing an Angular app, where i have to send data from angular forms to an external server using .netcore server and signalR. I am able to setup a connection between Angular client and controller using signalr hub but i am confused how to send json object from client to controller. From controller i want to send the Json object to external server. I want to implement this using signalr because i want realtime communication between external server and client. when i submit the data and recieve response from external server i want to alert client.I am looking for some guidance on how can i implement this.

Angular client

_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));

Controller

namespace ang.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DistController : Controller
    {
        private IHubContext<DistHub> _hubContext;
        public DistController(IHubContext<DistHub> hubContext)
        {
            _hubContext = hubContext;
        }
    }
}

SignalRhub

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);
        }
    }
}

startup.cs

app.UseSignalR(routes =>
{
    routes.MapHub<DistHub>("/message");
});

json object

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,
    }]
  },
}

2 Answers 2

2

You can do like this by passing in the root data to the invoke

connection.invoke('Send', "rk", "wassup", Root);

Then in your hub add another params for the root data

public async Task Send (string user , string message, string root)
{
  await Clients.All.SendAsync("Send", user, message);
}

Update since you are submit json string you can use

JsonConvert.DeserializeObject<List<object>>(root);
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @Tony Ngo, Thanks for your time. I have tried the above solution. How can i read the values from the "Root" object from Angular. I have created a model for the Root object in c# and it contains a class "root". Is it possible to display the data to console to verify if the data is correct.
You can run debug mode in visual studio
ok. I will check it. can you please explain what is "root" object. is it the Josn object "Root" or "root" class from the Root Model.
Seem like your json is not having the strong type so I think you can use object data in c#. You can check it here learn.microsoft.com/en-us/dotnet/csharp/language-reference/…
1

If the json data that you want to send from client is in known and fixed format, you can make your Hub method accept custom object parameter, like below.

Hub method

public async Task GetCustomData(string user, Root data)
{

    var sub_val2 = data.test1.sub[0].val2.ToString();

    //code logic here


    await Clients.All.SendAsync("ReceiveMessage", user, "{message_here}");
}

Custom Classes

public class Root
{
    public string Unit { get; set; }
    public List<Test> test { get; set; }
    public Test1 test1 { get; set; }
}

public class Test
{
    public bool Val { get; set; }
    public bool Val1 { get; set; }
}

public class Test1
{
    public List<Sub> sub { get; set; }
}

public class Sub
{
    public string val2 { get; set; }
    public string Val3 { get; set; }
}

Test Result

enter image description here

Besides, as Tony Ngo shared, modify Hub method to make it accept another object type parameter is also ok.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.