Establish a connection to the ActiveMQ broker utilizing STOMP protocol in an Ionic application

I've recently received an Ionic + Capacitor app that is primarily meant to run on the Android platform. My current task is to incorporate communication with a remote ActiveMQ broker into the app. To achieve this, I utilized the STOMP JS library which works seamlessly when tested on the browser. However, encountering connectivity issues when testing on the emulator led me to believe that the problem lies in the emulator's inability to understand the WS URL, unlike the browser which supports WebSockets by default. Researching online, I came across using SockJS as a potential simple solution and found a tutorial that may help in integrating it smoothly into my existing code:

Following the instructions provided in the tutorial and adding the fallback code resulted in encountering a strange error thrown by the Typescript compiler. Here is a snippet of my code:

import {Client, Message, ActivationState, messageCallbackType} from '@stomp/stompjs'
//import StompJs, { Message } from '@stomp/stompjs';
import { Queue } from 'queue-typescript';
import SockJS from 'sockjs-client';

const brokerEndpoint = "ws://localhost:61614";
//const brokerEndpoint = "ws://10.0.2.2:61614";

const items: string[] = [];
const queue = new Queue<string>(...items);

const createClient = () => {
    const client: Client = new Client({
        brokerURL: brokerEndpoint,
        connectHeaders: {
            login: 'admin',
            passcode: 'admin',
        },
        debug: function (str) {
            console.log(str);
        },
        reconnectDelay: 1000,
        heartbeatIncoming: 0,
        heartbeatOutgoing: 0
    });

    client.webSocketFactory = new SockJS('http://localhost:61613/stomp');

    /*
    if (typeof WebSocket !== 'function') {
        console.log("Not WebSocket");
        // For SockJS you need to set a factory that creates a new SockJS instance
        // to be used for each (re)connect
        client.webSocketFactory = function () {
            // Note that the URL is different from the WebSocket URL
            return new SockJS('http://10.0.2.2:15674/stomp');
        };
    } else {
        console.log("Still using WebSockets");
    }
    */

    return client;
}

const client: Client = createClient()

The error is triggered at the following line:

client.webSocketFactory = new SockJS('http://localhost:61613/stomp');

The compiler indicates that "Type 'WebSocket' is not assignable to type '() => IStompSocket'. Type 'WebSocket' provides no match for the signature '(): IStompSocket'."

Despite following the tutorial, there appears to be a conflict according to Typescript. Anyone who has experience working with SockJS + STOMP or any of the imported libraries successfully? Any assistance would be highly valued!

Answer №1

I encountered a similar issue to yours, which was caused by the version of the npm dependency @stomp/stompjs.

After some investigation, it appears that the developer who updated it made some changes but ended up creating confusion. They neglected to update the official documentation as well.

On the official website, it still states that the method webSocketFactory returns a WebSocket interface, when in reality, it returns IStompSocket. While these are meant to be similar, they are not interchangeable, and there's no documented way to convert a WebSocket to IStompSocket, leading to the failure.

Here is the solution:

1. Uninstall the current version by typing:

npm uninstall @stomp/stompjs

2. Install the same dependency with this specific version:

npm install @stomp/[email protected] --save

I hope this resolves your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

Is it possible to set the state of my datepicker to a previous value only if the new one is determined to be invalid?

I am currently facing an issue with a library I'm utilizing, which has the potential to generate incorrect values that may cause my page to crash. To prevent this, I want to ensure that only valid values (the result of useDateRangePickerState) are app ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...

Set up a custom key combination to easily toggle between HTML and TypeScript files that share the same name

Is it possible to set up a keyboard shortcut (e.g. Ctrl + `) to toggle between mypage.html and mypage.ts files? In my project, I have one HTML file and one TypeScript (TS) file with the same names. Ideally, I'd like to create a hotkey similar to F7 fo ...

Synchronize Docker volumes

Hey there! I've been trying to dive into learning Docker, but I'm having trouble syncing the host and container using volumes when making changes and saving code (specifically using npm run dev). Every time I need to restart docker-compose up --b ...

reusable angular elements

I'm facing a situation where I have a search text box within an Angular component that is responsible for searching a list of names. To avoid code duplication across multiple pages, I am looking to refactor this into a reusable component. What would b ...

The Angular tutorial for the "Tour of Heroes" is experiencing issues with aligning the heroes' list properly

I am currently working on the Angular tour of heroes tutorial. However, I am facing an issue when trying to display the list of heroes as it appears like this: It is strange because even though the CSS/HTML/TS code from the tutorial seems correct, the lis ...

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

Limit class generic to specify constructor argument type

I have a unique object that I need to transform into various structures based on its keys. Each key-value pair must be treated individually, so I intend to convert the object into an array of entries, then map those entries into policy objects and finally ...

There seems to be an issue with the TypeScript error: it does not recognize the property on the options

I have an item that looks like this: let options = {title: "", buttons: undefined} However, I would like to include a function, such as the following: options.open() {...} TypeScript is giving an error message: property does not exist on the options ty ...

React hook triggering re-render

A function has been implemented to retrieve and decode user claims from a token stored in local storage using a hook. export const useActiveUser = (): { user: IUserTokenClaims | null } => { const [user, setUser] = useState<IUserTokenClaims | nul ...

What is the best way to export a default object containing imported types in TypeScript?

I am currently working on creating ambient type definitions for a JavaScript utility package (similar to Lodash). I want users to be able to import modules in the following ways: // For TypeScript or Babel import myutils from 'myutils' // myuti ...

Getting a multitude of contacts exceeding 1000 with ngCordova in AngularJS

I am currently working on an app using the Ionic framework that allows users to view and select contacts from their device. I am utilizing ngCordova's $cordovaContacts module to retrieve the contacts. Here is the service code responsible for fetching ...

What is the process for creating an index signature for a type alias representing a Map in Typescript?

Suppose I have a custom type for a Map as follows: type MyCustomMap = Map<string, number>; Is there any way to add an index signature to this type so that I can set key-value pairs after initializing it? I have been able to achieve this with types ...

What is the best way to incorporate CSS from node_modules into Vite for production?

I have a TypeScript web application where I need to include CSS files from NPM dependencies in index.html. Here is an example of how it is done: <link rel="stylesheet" type="text/css" href="./node_modules/notyf/notyf.min.css&quo ...

Annoying glitch when using http get in Ionic (version 3.19.0)

Issue: Having trouble with Ionic's http get function, as I keep running into this error message: Typescript Error Expected 1-2 arguments, but got 3. The line causing the problem seems to be similar to this: this.http.get('http://127.0.0.1 ...

Customizing the Android Back Button behavior in NativeScript for a single specific page

I am currently using NativeScript version 5.2.4 along with TypeScript. My goal is to disable the back button functionality in one specific page only, but I'm facing an issue where it also disables the back button behavior for child pages. Below is the ...

What are the steps for creating and deploying a project that utilizes asp.net core on the server-side and Angular on the client-side

My latest project combines asp.net core 5 and angular 15 technologies for the backend and frontend, respectively. The asp.net core MVC portion of the project is contained in a dedicated folder named serverApi, while the angular part is generated in another ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...