Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
ngx-signalr-websocket
Advanced tools
Readme
A lightweight RxJS library that allows you to connect to ASP.NET SignalR using WebSocket. It is designed to provide simpler API.
This is based on the SignalR specification and uses the classes compatible with Angular. This ensures a small size of the extra code and good tree-shaking support.
package | version |
---|---|
rxjs | >= 7.0.0 |
Install ngx-signalr-websocket npm i --save ngx-signalr-websocket
.
Import SignalrClient and connect to SignalR hub:
import { SignalrClient } from 'ngx-signalr-websocket';
...
const client = SignalrClient.create(httpClient);
// constructor is also available: new SignalrClient(httpClient);
const connection = client.connect(signalrHubUri);
Next, subscribe to invocations.
connection.on<[TMessage]>('ReceiveMessage')
.subscribe(([message]) => ...)
...
Finally, when the job is done and you don`t need connection, you may disconnect:
connection.disconnect();
To send messages to the server сlients call public methods on hubs via the invoke()
method of the HubConnection. The invoke()
method accepts:
In the following example, the method name on the hub is 'SendMessage'
. The second and third arguments passed to invoke map to the hub method's 'user'
and 'message'
arguments:
connection.invoke<TData>('SendMessage', user, message)
.subscribe(data => ...);
If you only need to send a message to the server, you can use the send()
method. It does not wait for a response from the receiver.
connection.send<TData>('SendMessage', user, message);
To receive messages from the hub, define a method using the on()
method of the SignalrConnection.
In the following example, the method name is 'ReceiveMessage'
. The argument names are 'user'
and 'message'
:
connection.on<[string, string]>('ReceiveMessage')
.subscribe(([user, message]) => ...);
Another way to get messages from the service is by streaming. Clients call server-to-client streaming methods on hubs with stream()
method. The stream()
method accepts two arguments:
It returns an Observable, which contains a subscribe method. In the following example, the hub method name is 'Counter'
and the arguments are a count for the number of stream items to receive and the delay between stream items.
connection.stream<TItem>('Counter', 10, 500)
.subscribe(item => ...);
To end the stream from the client, call the unsubscribe()
method on the ISubscription that's returned from the subscribe method. Or wait until the server invokes CompletionMessage.
With the default configuration, the client converts JSON as is.
If you want to override the configuration, you can use the constructor parameter:
SignalrClient.create(url, configuration => {
confgiuration.propertyParsers = []; // This is default value.
})
If you need specific settings for message parsing, you can add functions (name: string, value: any) => any
to the propertyParsers
option. If you need a Date conversion, just add parseIsoDateStrToDate
to propertyParsers
.
The following example demonstrates the SignalR client usage in the Angular service.
It uses NgRx to provide SignalR Hub URL. In general, this is not necessary, but the example shows how it can be applied.
import { HttpClient } from '@angular/common/http';
import { Injectable, OnDestroy } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable, BehaviorSubject } from 'rxjs';
import { filter, switchMap, withLatestFrom, map } from 'rxjs/operators';
import { SignalrClient, SignalrConnection } from 'ngx-signalr-websocket';
import * as fromRoot from '@app/store/reducers';
...
@Injectable({
providedIn: 'root'
})
export class AppSignalrService implements OnDestroy {
private client: SignalrClient;
private connection$ = new BehaviorSubject<SignalrConnection | null>(null);
private readonly readyConnection$ = this.connection$.pipe(filter(connection => !!connection && connection.opened));
constructor(store: Store<fromRoot.State>, httpClient: HttpClient) {
this.client = SignalrClient.create(httpClient);
store.select(fromRoot.selectSignalrHubUri)
.pipe(
switchMap(uri => this.client.connect(uri)),
retryWhen(errors => errors.pipe(
tap(error => console.error(`SignalR connection error: ${error}`)),
delay(5000)
)))
.subscribe(connection => {
this.disconnect();
this.connection$.next(connection);
});
}
getLastMessages(): Observable<string[]> {
return this.readyConnection$
.pipe(switchMap(connection => connection.invoke<string[]>('GetLastMessages', 10)));
}
sendMessage(user: string, message: string): void {
return this.readyConnection$
.pipe(switchMap(connection => connection.send('SendMessage', user, message)));
}
onReceiveMessage(): Observable<{ user: string, message: string }> {
return this.readyConnection$
.pipe(
switchMap(connection => connection.on<[string, string]>('ReceiveMessage')),
map(([user, message]) => { user, message }));
}
getUserMessagesStream(user: string): Observable<string> {
return this.readyConnection$
.pipe(switchMap(connection => connection.stream<string>('GetUserMessagesStream', user)));
}
ngOnDestroy(): void {
this.disconnect();
}
private disconnect(): void {
if (this.connection$.value) { this.connection$.value.close(); }
}
}
FAQs
A lightweight ASP.NET SignalR client for Angular
The npm package ngx-signalr-websocket receives a total of 287 weekly downloads. As such, ngx-signalr-websocket popularity was classified as not popular.
We found that ngx-signalr-websocket demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.