Coder Social home page Coder Social logo

jimic / ng2-stompjs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from stomp-js/ng2-stompjs

0.0 2.0 0.0 2.35 MB

Angular 2, 4 and 5 - Stomp service over Websockets

Home Page: https://stomp-js.github.io/ng2-stompjs/

License: MIT License

Shell 1.33% TypeScript 90.95% JavaScript 6.96% HTML 0.75%

ng2-stompjs's Introduction

@stomp/ng2-stompjs

Build Status

An Angular (Angular2, Angular4, ...) style wrapper for @stomp/stompjs.

Compatibility

Tested with Angular CLI generated Angular2 (2.4.0), Angular4 (4.0.0), Angular (5.0.0). It has been reported to work with ionic projects as well.

Installation

To install this library, run:

$ npm install @stomp/ng2-stompjs --save

or, if using yarn:

$ yarn add @stomp/ng2-stompjs

This will additionally install @stomp/stompjs from https://github.com/stomp-js/stomp-websocket

Usage

Prerequisites

  • You will need to have a Stomp broker running.
  • The sample code on this page assumes you have RabbitMQ running with default settings and Web STOMP plugin activated. (see: https://www.rabbitmq.com/web-stomp.html.)

All the Hard Work

    const stompConfig: StompConfig = {
      // Which server?
      url: 'ws://127.0.0.1:15674/ws',
    
      // Headers
      // Typical keys: login, passcode, host
      headers: {
        login: 'guest',
        passcode: 'guest'
      },
    
      // How often to heartbeat?
      // Interval in milliseconds, set to 0 to disable
      heartbeat_in: 0, // Typical value 0 - disabled
      heartbeat_out: 20000, // Typical value 20000 - every 20 seconds
    
      // Wait in milliseconds before attempting auto reconnect
      // Set to 0 to disable
      // Typical value 5000 (5 seconds)
      reconnect_delay: 5000,
    
      // Will log diagnostics on console
      debug: true
    };
  providers: [
    StompService,
    {
      provide: StompConfig,
      useValue: stompConfig
    }
  ]

Reap the Benefits

Inject StompService

In your constructor (typically of a component or a service), inject StompService as a dependency:

constructor(private _stompService: StompService) { }

Subscribe to a queue

The queue name structure and semantics vary based on your specific STOMP Broker, see: https://www.rabbitmq.com/stomp.html for RabbitMQ specific details.

Call subscribe(queueName: string, headers: StompHeaders = {}) with name of the queue which returns an Observable (details at: https://stomp-js.github.io/ng2-stompjs/classes/stompservice.html#subscribe). Any of Observable specific operators (map, filter, subscribe, etc.) can be applied on it. This can also be set into a template with async pipe.

Example:

    let stomp_subscription = this._stompService.subscribe('/topic/ng-demo-sub');

    stomp_subscription.map((message: Message) => {
      return message.body;
    }).subscribe((msg_body: string) => {
      console.log(`Received: ${msg_body}`);
    });

The Message class comes from @stomp/stompjs. So, you will need the following import in the classes where you consume messages:

import {Message} from '@stomp/stompjs';

Unsubscribe from a queue

You will need to unsubscribe from stomp_subscription (which is an Observer), it will then internally unsubscribe from the underlying STOMP queue subscription.

Publishing messages

Call publish(queueName: string, message: string, headers: StompHeaders = {}) (details at: https://stomp-js.github.io/ng2-stompjs/classes/stompservice.html#publish). Example:

this._stompService.publish('/topic/ng-demo-sub', 'My important message');

Please note that message is actually string. So, if you need to send JSON you will need to convert it into string (typically using JSON.stringify())

Watching for Stomp connection status

  • stompService.state is a BehaviorSubject which maintains and switches its value as per the underlying Stomp Connection status.
  • The value is from an enum with these possible values:
    • CLOSED
    • TRYING
    • CONNECTED
    • DISCONNECTING
  • The following code will subscribe to stompService.state and convert the enum value (which is a number) to the corresponding string value:
    this._stompService.state
      .map((state: number) => StompState[state])
      .subscribe((status: string) => {
      console.log(`Stomp connection status: ${status}`);
    });

If you are interested in watching only when connection is established, you can subscribe to this._stompService.connectObservable.

Delayed initialization

It is usually possible to use Angular dependency injection techniques and APP_INITIALIZER to delay the initialization till the configuration is ready (may be fetched using an API call.) See a sample at: https://github.com/stomp-js/ng2-stompjs-demo

The initialization process can be manually controlled with the additional class StompRService which is injected instead of StompService. This has a few additional methods to assign a configuration and manually initiate the connection to the STOMP Broker.

// Do not provide StompService or StompConfig, only provide StompRService

  providers: [
    StompRService
  ]
class YourClass {}
    constructor(private _stompService: StompRService) { }
    
    public initStomp() {
      StompConfig config;
  
      cofig = this.fetchConfigFromSomeWhere();
      
      this._stompService.config = config;
      this._stompService.initAndConnect();
    }
}

The methods subscribe and publish can be called even before call to initAndConnect. However these will be queued till the actual connection is successful.

For the curious - initAndConnect may be called more than once with a potentially updated configuration.

Contributors

License

MIT

ng2-stompjs's People

Contributors

janwytze avatar kum-deepak avatar timhovius avatar tplk avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.