Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork0
Angular service for integrating RSocket communication into your Angular application
License
saleweaver/angular-rsocket
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
An Angular service for integrating RSocket communication into your Angular applications, leveraging Angular’s Signals and dependency injection system. This service allows you to easily connect to an RSocket server, handle streams and messages, and manage authentication tokens flexibly via a token provider.
RSocket Integration: Seamlessly integrate RSocket communication into your Angular application.
Angular Signals: Utilize Angular’s reactive Signal system for real-time data updates.
Flexible Token/Auth Management: Provide authentication tokens via configuration or a custom TokenProvider.
Automatic Reconnection: Configurable automatic reconnection logic with retry attempts and delays.
To install the Angular RSocket Service, simply run:
npm install @michaeldatastic/angular-rsocket
Thank you for considering contributing to the Angular RSocket Service Library! We welcome all types of contributions including bug fixes, new features, documentation improvements, and more.Please seeContributing.md for more information on how to contribute to this project.
- Configuration
In your application’s configuration, provide the RSocket service using the provideRSocket function. This function allows you to specify the RSocket connection configuration and an optional custom token provider.
// app.config.tsimport{ApplicationConfig}from'@angular/core';import{provideRouter}from'@angular/router';import{provideZoneChangeDetection}from'@angular/core';import{provideRSocket}from'@michaeldatastic/angular-rsocket';import{routes}from'./app.routes';exportconstappConfig:ApplicationConfig={providers:[provideZoneChangeDetection({eventCoalescing:true}),provideRouter(routes),provideRSocket({url:'ws://localhost:8080/rsocket',// Other optional configurations can be specified here}),],};
- Injecting and Using the RSocket Service in a Custom Service
It’s recommended to handle subscriptions and data sharing in your own services. This allows you to control how subscriptions are managed and whether they are reused or not.
// board-updates.service.tsimport{Injectable}from'@angular/core';import{RSocketService}from'@michaeldatastic/angular-rsocket';import{Signal}from'@angular/core';@Injectable({providedIn:'root',})exportclassBoardUpdatesService{publicupdates$:Signal<any[]|null>;constructor(privatersocketService:RSocketService){// Create a subscription to the 'board.updates' streamthis.updates$=this.rsocketService.requestStream<any>('board.updates');}}
- Using the Custom Service in a Component
Finally, you can use your custom service in a component to display real-time updates from the RSocket server.
// app.component.tsimport{Component,effect,inject}from'@angular/core';import{BoardUpdatesService}from'./board-updates.service';import{Signal}from'@angular/core';@Component({selector:'app-root',template:` <div *ngIf="updates$()"> <div *ngFor="let item of updates$()"> <!-- Display your streamed data here --> {{ item | json }} </div> </div> `,})exportclassAppComponent{privateboardUpdatesService:BoardUpdatesService=inject(BoardUpdatesService);updates$:Signal<any[]|null>;constructor(){this.updates$=this.boardUpdatesService.updates$;effect(()=>{console.log('Received Stream Data:',this.updates$());});}}
- Passing an Authentication Token
If your RSocket server requires authentication, you can provide a token in the configuration:
provideRSocket({url:'ws://localhost:8080/rsocket',token:'your-authentication-token',});
For more advanced token management, such as retrieving tokens from an authentication service or handling token refresh logic, you can provide a custom TokenProvider.First, create a custom token provider by implementing the AngularRSocketTokenProvider interface:
// InterfaceexportinterfaceAngularRSocketTokenProvider{getToken():string|Signal<string>|null;}
// custom-token-provider.tsimport{Injectable,inject}from'@angular/core';import{AngularRSocketTokenProvider}from'@michaeldatastic/angular-rsocket';import{AuthService}from'./auth.service';import{Signal,signal,effect}from'@angular/core';@Injectable()exportclassCustomTokenProviderimplementsAngularRSocketTokenProvider{privateauthService:AuthService=inject(AuthService);privatetokenSignal:Signal<string>;constructor(){// Initialize the token signal with the current tokenthis.tokenSignal=signal(this.authService.getToken());// Update the token signal whenever the token changeseffect(()=>{this.tokenSignal.set(this.authService.getToken());});}getToken():string|Signal<string>{returnthis.tokenSignal;}}
Then, provide the custom token provider in your application configuration:
// app.config.tsimport{CustomTokenProvider}from'./custom-token-provider';exportconstappConfig:ApplicationConfig={providers:[// ... other providersprovideRSocket({url:'ws://localhost:8080/rsocket',// Other configuration options},CustomTokenProvider// Pass the custom token provider class),],};
- Advanced Configuration Options
The provideRSocket function accepts an AngularRSocketConfig object with the following optional properties, only url is required:
import{IdentitySerializer,JsonSerializer}from"rsocket-core";provideRSocket({url:'ws://localhost:8080/rsocket',// RSocket server URL *<required>*dataSerializer:IdentitySerializer|JsonSerializer,// Custom data serializermetadataSerializer:IdentitySerializer|JsonSerializer,// Custom metadata serializerkeepAlive:60000,// Keep-alive interval in millisecondslifetime:180000,// Connection lifetime in millisecondsdataMimeType:WellKnownMimeType.APPLICATION_JSON,// Data MIME typemetadataMimeType:WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA,// Metadata MIME typemaxReconnectAttempts:5,// Max reconnection attemptsreconnectDelay:2000,// Delay between reconnection attempts in millisecondstoken:'your-authentication-token',// Authentication token (string or Signal)});
- Managing Subscriptions
Since this is a library, it’s up to you to decide how to manage subscriptions and whether to reuse them. If you call requestStream multiple times with the same route, each call will create a new subscription to the RSocket stream.
Important Note: Multiple subscriptions to the same route can lead to increased server load and redundant data processing. If you want to reuse subscriptions, consider managing them in a shared service, as shown in the example above.
- Handling Disconnections
The RSocketService automatically attempts to reconnect based on the configuration. You can also manually disconnect by calling the disconnect method.
// In your custom service or componentthis.rsocketService.disconnect();
Note: Be cautious when manually disconnecting, as it will affect all components using the shared RSocketService instance.
- Additional Methods
The RSocketService provides several methods for different interaction models:
requestStream<T>(route:string,data?:any,requestItems?:number):WritableSignal<T[]|null>requestResponse<T>(route:string,data:any):WritableSignal<T|null>fireAndForget(route:string,data:any):voidchannel<T>(route:string,dataIterable:Iterable<any>,requestItems?:number):WritableSignal<T|null>
- Example: Using requestResponse in a Custom Service
// data-service.tsimport{Injectable}from'@angular/core';import{RSocketService}from'@michaeldatastic/angular-rsocket';import{Signal}from'@angular/core';@Injectable({providedIn:'root',})exportclassDataService{constructor(privatersocketService:RSocketService){}getData():Signal<any|null>{returnthis.rsocketService.requestResponse<any>('your.route',{some:'data'});}}
// component.tsimport{Component,effect}from'@angular/core';import{DataService}from'./data-service';import{Signal}from'@angular/core';@Component({selector:'app-data',template:` <div *ngIf="data$()"> <!-- Display your data here --> {{ data$() | json }} </div> `,})exportclassDataComponent{data$:Signal<any|null>;constructor(privatedataService:DataService){this.data$=this.dataService.getData();effect(()=>{console.log('Received Response Data:',this.data$());});}}
This project is licensed under the MIT License - see the LICENSE file for details.
About
Angular service for integrating RSocket communication into your Angular application
Resources
License
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.