Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data sent from web api using signalr in angular?

I want to read data sent from asp.net web api through signalr in angular client.

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

and in angular client ,

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

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 .

like image 560
Tejas Avatar asked Jan 27 '26 21:01

Tejas


1 Answers

Edit: Only for asp.net core

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

Update

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

You can view here

like image 98
Tony Ngo Avatar answered Jan 30 '26 13:01

Tony Ngo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!