
Security News
npm Adopts OIDC for Trusted Publishing in CI/CD Workflows
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
ngx-signalr-websocket
Advanced tools
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);
// you can use both Angular HttpClient and DefaultHttpPostClient from this lib;
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.
If you want to override the configuration, you can use the constructor parameter:
SignalrClient.create(httpClient, options => {
options.headersFactory = (_method: string, _arg: unknown[]) =>
of({
['User']: '101',
});
options.propertyParsers = [parseIsoDateStrToDate]
})
If you need extra headers for SignalR methods call, use headersFactory
option.
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 { BehaviorSubject, filter, map, Observable, switchMap, withLatestFrom } from 'rxjs';
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 627 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 0 open source maintainers 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.
Security News
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
Research
/Security News
A RubyGems malware campaign used 60 malicious packages posing as automation tools to steal credentials from social media and marketing tool users.
Security News
The CNA Scorecard ranks CVE issuers by data completeness, revealing major gaps in patch info and software identifiers across thousands of vulnerabilities.