Makes using SignalR in Angular 2/4 easy.
Set up a new project using @angular/cli
npm install --save ngx-signalr-hubservice
Add the jquery and SignalR scripts to your angular-cli.json"scripts":
Import the HubService and add it to your providers in your
app.module.ts. Mine looks like this(I've included FormsModule for the demo):;;;;;
Inject the hub service in (probably) your root component. In this case it's
app.component.ts. Make sure you import the service. Here you can make the connection.constructorprivate hubService: HubService......async ngOnInit
For my applications I generally just reference the HubService in my other services(one service for each hub), and expose the hub methods/events through those services. For a demo this works too though.
Define a class that will interact with the SignalR server. For me it's just the root
AppComponent. You can use the
@Hubdecorator on the class to define what hub this class connects to.;;;// <-- Your hub declaration
Define a method that the hub will call with @HubSubscription in the same class. You can pass in the method name in the decorator, or just leave it blank. If left blank, the service will use the name of the method that you added the decorator to as the subscription name. NOTE: you generally have to run these callbacks inside angular's zone if you're updating UI. Hopefully future versions you won't have to do this.receiveMessageparam1: any, param2: any
For calling methods on the hub, you need to register this class with the hub service.
Update your constructor to this, and add a new field on your class:private hubWrapper: HubWrapper;constructorprivate hubService: HubService
Now you can call methods on the hub using this hub wrapper,callHubMethod
You can unregister hub wrappers from the service with
hubService.unregister(this);. Generally you wouldn't want to do this because you'll call SignalR from services that exist during the lifetime of your application.ngOnDestroy
You can use the
hubGroups parameter on the
@Hub decorator if you have two or more SignalR connections being made and want to control which
@Hub decorators are applying to which connection.
You can see an example of this here:
@Inject decorator on the constructors of the services. You need to specify which connection you want to inject into your service if you're using multiple HubServices. Remember to provide your HubService's correctly too with the proper
// Probably at the top of your NgModule;;...// In your NgModule decoratorproviders:
If you want to get the underlying SignalR instances, you can access them through
HubService.connectionfor the SignalR connection instance(
$.connection). You can access the SignalR hub instances for the individual hubs through
If you pass
attemptReconnectsas true to
HubService.connectoptions parameter, any
invokecalls on your HubWrappers will defer until the HubService reconnects. They will most likely not error.