Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A lightweight ASP.NET SignalR client for Angular

License

NotificationsYou must be signed in to change notification settings

yurivoronin/ngx-signalr-websocket

Repository files navigation

A lightweight RxJS library that allows you to connect toASP.NET SignalR using WebSocket. It is designed to provide simpler API.

This is based on theSignalR specification and uses the classes compatible with Angular. This ensures a small size of the extra code and good tree-shaking support.

Features

  • Depends only on RxJS
  • Compatible with Angular HttpClient, but this is not necessary
  • Implements the usual reactive API for Angular developers
  • Provides good typing support
  • Allows to configure messages serialization
  • Allows to authorize using access token
  • Supports WebSockets transport and Text transfer format (JSON)

Dependencies

packageversion
rxjs>= 7.0.0

Getting started

  1. Install ngx-signalr-websocketnpm i --save ngx-signalr-websocket.

  2. Import SignalrClient and connect to SignalR hub:

    import{SignalrClient}from'ngx-signalr-websocket';...constclient=SignalrClient.create(httpClient);// constructor is also available: new SignalrClient(httpClient);// you can use both Angular HttpClient and DefaultHttpPostClient from this lib;constconnection=client.connect(signalrHubUri);
  3. Next, subscribe to invocations.

    connection.on<[TMessage]>('ReceiveMessage').subscribe(([message])=> ...)...
  4. Finally, when the job is done and you don`t need connection, you may disconnect:

    connection.disconnect();

Send message

To send messages to the server сlients call public methods on hubs via theinvoke() method of the HubConnection. Theinvoke() method accepts:

  • the name of the hub method
  • any arguments defined in the hub method

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 thesend() method. It does not wait for a response from the receiver.

connection.send<TData>('SendMessage',user,message);

Receive messages

To receive messages from the hub, define a method using theon() 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])=> ...);

Streaming

Another way to get messages from the service is by streaming. Clients call server-to-client streaming methods on hubs withstream() method. Thestream() method accepts two arguments:

  • The name of the hub method
  • Arguments defined in the hub method

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 theunsubscribe() method on the ISubscription that's returned from the subscribe method. Or wait until the server invokes CompletionMessage.

Configuration

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, useheadersFactory option.

If you need specific settings for message parsing, you can add functions(name: string, value: any) => any to thepropertyParsers option. If you need a Date conversion, just addparseIsoDateStrToDate topropertyParsers.

Service example

The following example demonstrates the SignalR client usage in the Angular service.

It usesNgRx 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*asfromRootfrom'@app/store/reducers';...@Injectable({providedIn:'root'})exportclassAppSignalrServiceimplementsOnDestroy{privateclient:SignalrClient;privateconnection$=newBehaviorSubject<SignalrConnection|null>(null);privatereadonlyreadyConnection$=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[]>{returnthis.readyConnection$.pipe(switchMap(connection=>connection.invoke<string[]>('GetLastMessages',10)));}sendMessage(user:string,message:string):void{returnthis.readyConnection$.pipe(switchMap(connection=>connection.send('SendMessage',user,message)));}onReceiveMessage():Observable<{user:string,message:string}>{returnthis.readyConnection$.pipe(switchMap(connection=>connection.on<[string,string]>('ReceiveMessage')),map(([user,message])=>{user,message}));}getUserMessagesStream(user:string):Observable<string>{returnthis.readyConnection$.pipe(switchMap(connection=>connection.stream<string>('GetUserMessagesStream',user)));}ngOnDestroy():void{this.disconnect();}privatedisconnect():void{if(this.connection$.value){this.connection$.value.close();}}}

About

A lightweight ASP.NET SignalR client for Angular

Resources

License

Stars

Watchers

Forks

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp