The functionality of the Vert.x event bus client is limited in Angular 7 when not used within a constructor

I have been attempting to integrate the vertx-eventbus-client.js 3.8.3 into my Angular web project with some success. Initially, the following code worked perfectly:

declare const EventBus: any;

@Injectable({
    providedIn: 'root'
})
export class DeviceService implements OnInit {

    constructor(private httpClient: HttpClient) {

       var eb = new EventBus("http://127.0.0.1:8080/eventbus");

       eb.onopen = function() {

          eb.registerHandler("events-feed", function(error, message) {
              console.log("Message: " + message.body);
          });

          eb.registerHandler("receiver", function(error, message) {
             console.log('Message: ' + message.body);
          });

          eb.publish("events-feed", "Test", function (error, message) {
              console.log(JSON.parse(message.body));
          });
      }

    }

}

The connection is successfully established with the backend and I am able to receive messages through the registerHandler method. However, when I try to move this code within a function like so:

private eb : any;

initializeEventBus() {
     this.eb = new EventBus("http://127.0.0.1:8080/eventbus");

       this.eb.onopen = function() {

          this.eb.registerHandler("events-feed", function(error, message) {
              console.log("Message: " + message.body);
          });

          this.eb.registerHandler("receiver", function(error, message) {
             console.log('Message: ' + message.body);
          });

          this.eb.publish("events-feed", "Test", function (error, message) {
              console.log(JSON.parse(message.body));
          });
      }

}

An error occurs and I receive the following error message:

core.js:14597 ERROR TypeError: Cannot read property 'registerHandler' of undefined
    at EventBus.DeviceService.eb.onopen (device.service.ts:28)
    at w.self.sockJSConn.onopen (vertx-eventbus.js:121)
    at w.r.dispatchEvent (eventtarget.js:51)
    at w._open (main.js:320)
    at w._transportMessage (main.js:253)
    at u.i.emit (emitter.js:50)
    at WebSocket.ws.onmessage [as __zone_symbol__ON_PROPERTYmessage] (websocket.js:35)
    at WebSocket.wrapFn (zontext.js:1332)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:16147)

Any insights on what may be going wrong here would be greatly appreciated.

Best regards

Answer №1

When you utilize this keyword, it does not get bound. To correct this issue, you should employ an arrow function as shown below:

this.eb.onopen = () => {

          this.eb.registerHandler("events-feed", (error, message) => {
              console.log("Message: " + message.body);
          });

          this.eb.registerHandler("receiver",  (error, message) => {
             console.log('Message: ' + message.body);
          });

          this.eb.publish("events-feed", "Test",  (error, message) => {
              console.log(JSON.parse(message.body));
          });
      }

I trust this solution proves helpful.

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

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

Preventing the display of the login page for an authenticated user in Angular

My application has different modules for authentication, dashboard, and root routing. The auth module contains routes for sign-in, the dashboard module has routes for home with authentication guard, and the root module redirects to home or a PageNotFound c ...

Obtain JSON information in a structured model layout using Angular 4

I have different categories in the backend and I would like to retrieve them in a model format. Here is how my model is structured: export class Category { name: string; id : string; } And this is how the data appears in the backend: { "name": "cars", ...

Triggering multiple subscription functions in Ionic 3 NGRX when a single state change occurs

I have developed an Ionic 3 application that utilizes NGRX for state management purposes. The app is designed to connect to a device via BLE technology. Within my connection page, where the BLE device is connected, I have implemented the following code: ...

Navigating back to the login page in your Ionic V2 application can be achieved by utilizing the `this.nav

Running into an issue with navigating back to the login screen using Ionic V2. Started with the V2 tabs template but added a custom login page, setting rootPage = LoginPage; in app.components.ts. When the login promise is successful, I used this.nav.setR ...

Navigate to a nested page in React router and automatically open a new page whenever there are parameters passed

I am currently using create-react-app to build my project and I am working on implementing dynamic routing. My site has three main pages: Accordion, Movies, and MovieDetail. The Movies page displays a list of movies fetched from swapi. The goal is to have ...

Inquiring about Vue 3 with TypeScript and Enhancing Types for Compatibility with Plugins

I've been struggling to find a working example of how to implement type augmentation with Vue3 and TypeScript. I have searched for hours without success, trying to adapt the Vue2 documentation for Vue3. It appears that the Vue object in the vue-class ...

Create type definitions for React components in JavaScript that utilize the `prop-types` library

Exploring a component structure, we have: import PropTypes from 'prop-types'; import React from 'react'; export default class Tooltip extends React.Component { static propTypes = { /** * Some children components */ ...

Prevent the Mat Dialog from showing up depending on the situation

I am attempting to prevent a Mat Dialog from appearing unless a specific condition is met. I originally thought about using Angular Guard, but since there is no associated route with the component (besides the main webpage it's called from), that appr ...

Tips for simulating a "nested" angular service within a component using jest

I'm looking to create a unit test for an Angular Component using Jest. The component, which is built on Angular version 7.2.0, interacts with a nested service through this.api.manageUser.getUsersStats(). My goal is to verify if this method is being ca ...

What is the procedure for transferring the inputted data from an HTML file to its corresponding TS file and subsequently to a different component file?

I have created two components, a login and a home-page. I am attempting to capture user input from the login template, pass it to the login component, and then display it on the home-page template using the home-page component. What is the best approach to ...

The Sequence of Import Statements in Angular 2

The Angular Style Guide provides recommendations on Import line spacing: It is suggested to include one empty line between third-party imports and application imports. Consider arranging import lines in alphabetical order based on the module. For destruc ...

Is there a way to turn off TypeScript Inference for imported JavaScript Modules? (Or set it to always infer type as any)

As I attempt to utilize a JS module within a TypeScript File, I encounter errors due to the absence of type declarations in the JS module. The root cause lies in a default argument within the imported JS function that TypeScript erroneously interprets as ...

Overriding a shared module service in Angular from a separate module: A step-by-step guide

I am working with various modules such as SchoolModule, UniversityModule, and SharedModule The SharedModule includes a BaseService that both the SchoolModule and UniversityModule providers are utilizing as an extension When loading the SchoolModule, I ne ...

Unable to attach to 'aria-valuenow' as it's not recognized as a property of 'div'

I encountered an issue when attempting to assign an expression to an element. The problem arose with the following code: <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="{{MY_PREC}}" aria-valuemin="0" aria-value ...

What Causes CORS Errors When Sending Encoded Information?

Dealing with poor data quality is a challenge I face. An example of this is when the primary key value of a table contains spaces and special characters, like 35581/H0034-100003 My goal is to retrieve a record by its primary key value using a GET request ...

Having trouble loading image on web application

Currently, I am facing an issue while attempting to add a background image to an element within my Angular web application. Strangely enough, the relative path leading to the image seems to be causing my entire app to break. https://i.stack.imgur.com/b9qJ ...

The ag-Grid cellDoubleClicked event seems to be triggered twice when the cell is double clicked quickly, but functions correctly when double clicking at a slower

Currently, I am facing an issue in my Angular 8 project while using Ag-grid. The problem arises when I try to handle the double click event in ag-grid. Whenever the cellDoubleClicked event is triggered, a method is called twice if I quickly double click on ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...