-
Dependency: Before add the lib to your project, install de signalr official lib (click here or):
npm install @microsoft/[email protected]
You can install the library using:
npm:
npm install ngx-b-signalr
-
Add the BSignalrModule to your
app.module.ts
and import your environment variable:@NgModule({ declarations: [ ... ], imports: [ ... BSignalrModule.forRoot(environment), ], })
-
Implement the interface SignalRConfig to environment.ts and set the url for you signalr server:
export const environment: SignalRConfig | any = { ..., signalrEndpoint: "http://localhost:7001/hub" }
-
Call startup method in your app.component.ts or in application initializer:
export class AppComponent { title = '...'; constructor(private signalRService : SignalRService) { this.signalRService.connect(); } }
The library provides an easy interface to connect to your Signal-R server.
Create a subscription:
The subscription is a way to receive messages from a specified room.
-
Instance a new SignalRSubscription and listen for a message room:
import { SignalRService, SignalRSubscription } from 'ngx-b-signalr'; ... subscription! : SignalRSubscription<CollectorState>; constructor(private signalRService : SignalRService) { this.subscription = this.signalRService.buildSubscription(`ROOM`); this.subscription.OnMessageReceived$.subscribe(x => { console.log('Response: ', x); } }
-
Always call .destroy() on your OnDestroy() method to unsubscribe:
ngOnDestroy(): void { this.subscription.destroy(); }
Framework | Version |
---|---|
Angular | 13.x.x |
@microsoft/signalr | 6.0.5 |
Microsoft.AspNetCore.SignalR | 1.1.0 |
Tip: The lib was not tested in previous versions of angular, fell free to give us a feedback ;)