2

I am trying to use signalr in angular. I have a working hub in c# with a function called Hello

public class myHub : Hub
{
    public void Hello(string msg)
    {
        Console.WriteLine("HIIII" + msg);
    }
}

I am using angular 5 and the package ng2-signalr, but I don't understand how to create a connection. I tried to follow the documentation but I couldn't understand the flow of the code. can anyone point me to a guide or perhaps give a simple example

Yedidya kfir
  • 1,419
  • 3
  • 17
  • 32

1 Answers1

0

I did actually get it connected.

Follow the documentation for the app.module.ts for version > 2

import { SignalRModule } from 'ng2-signalr';
import { SignalRConfiguration } from 'ng2-signalr';

 // >= v2.0.0
 export function createConfig(): SignalRConfiguration {
 const c = new SignalRConfiguration();
 c.hubName = 'name of your hub'; 
 c.qs = { user: 'donald' };
 c.url = 'https://url to root of your service';
 c.logging = true;

 // >= v5.0.0
 c.executeEventsInZone = true; // optional, default is true
 c.executeErrorsInZone = false; // optional, default is false
 c.executeStatusChangeInZone = true; // optional, default is true
 return c;
}

The important thing to note is the name of the hub (myHub in your case) and just enter the root to your service. The package will add the signalr route

Add this to the end of your imports just as the documentation states

SignalRModule.forRoot(createConfig)

I then just attempted to inject the connection into a single component.

// inside your component.
  constructor(private _signalR: SignalR)  {
}

ngOnInit() {
  this._signalR.connect().then((c) =>console.log("Connected")); 


}

The obstacle I ran into was cors in my service. In the startup.cs this is my Configuration

public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            map.RunSignalR(new HubConfiguration()
            {
                EnableDetailedErrors = true,
                EnableJavaScriptProxies = true
            });
        });
    }

This allowed me to successfully connect to the hub.

Jeff
  • 3
  • 1