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

Issue: The use of destructuring props is required by eslint, and I'm currently working with a combination of react and types

I typically work with React in JavaScript, and I recently encountered an error message stating "Must use destructuring props at line 14" while trying to define a button for use in a form. Here is the code snippet in question: import React from 'react& ...

Setting the value of a form control within a form array in an Angular reactive form can be achieved by following these steps

I have a reactive form with multiple entity entries: this.entityDetailsForm = new FormGroup({ entitiesArray: new FormArray([ new FormGroup({ id: new FormControl(), name: new FormControl(), startDate: new Form ...

An error has occurred in Node.js/Express.js: The path argument is missing and is required for res.sendFile

I have successfully uploaded my files using Multer to a specific directory. However, I am now facing an issue while trying to download the same files that are displayed in an HTML table with individual download options. Below is the code snippet: Node.j ...

How to initiate focus on Angular 2 MdInputContainer after the view has been

I am encountering an issue with setting focus on the first md-input-container element within a component when the view loads. Despite implementing a @ViewChild property and calling focus on it in the ngAfterViewInit method, the focus does not seem to be wo ...

Sending a POST request with parameters using HttpClient

My current challenge involves making a POST request to an endpoint that requires query string parameters instead of passing them in the body of the request. const params = new HttpParams() .set('param1', '1') .set('param2' ...

Encountering an issue in Angular 4 AOT Compilation when trying to load a Dynamic Component: Error message states that the

My Angular application is facing challenges when loading dynamic components. Everything works smoothly with the JIT ng serve or ng build compilation. Even with AOT ng serve --prod or ng build --prod, I can still successfully build the application. Lazy loa ...

Gatsby struggles with generating Contentful pages using TypeScript

I have been working on creating dynamic pages with Contentful in Gatsby + Typescript. While I am able to fetch data successfully using GraphQL in a browser, I encounter issues when trying to fetch data in gatsby-node.ts. The pages seem to be generated part ...

A perplexing issue arises in Angular 8 where a component placed between the header and footer fails to display, despite no errors being

I've encountered an issue with angular routing that I need assistance with. In the app.component.html file, we have: <router-outlet></router-outlet> The configuration in the app-routing.module.ts looks like this: import { NgModule } fr ...

The hook from Supabase is facing issues with proper importing

This project is a Spotify clone. The issue I'm facing is related to importing the hook. The error message reads: React Hook "useSupabaseClient" is called in function "useloadArtistImage" that is neither a React function component nor a custom React H ...

Challenges with deploying an AngularJS application on a WebSphere Application Server (W

I have been attempting to package my spring boot webservice and Angular 6 app into a war file for deployment on WebSphere Application Server 8.5. I created a sample Angular app and ran "ng build --prod". Following the guidelines provided in this answer, I ...

Executing asynchronous methods in a Playwright implementation: A guide on constructor assignment

My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of ...

Attempting to execute a synchronous delete operation in Angular 6 upon the browser closing event, specifically the beforeunload or unload event

Is there a way to update a flag in the database using a service call (Delete method) when the user closes the browser? I have tried detecting browser close actions using the onbeforeunload and onunload events, but asynchronous calls do not consistently wor ...

Guide to implementing basic authentication within an HTTP request in Angular 4

I'm new to this and I only have experience with the http post method. I need to send the username and password as base authentication for every API request. onSubmit = function(userdata){ this.tokenkey = localStorage.getItem('logintoken&apos ...

item uploaded via internet not restricted

Recently delving into Angular2, I am currently engrossed in constructing a basic application that showcases a list of objects. My goal is to click on one object and delve into a detailed view of it. However, while attempting to access the properties of the ...

What could be the reason for the ERROR message saying, "Cannot read property '0' of undefined"?

I'm really struggling to understand why I keep receiving an Undefined error for tagged_Assets. Can someone please shed some light on this for me? Thank you. Model.ts export class TaggedAssests { device_id: string; hasTag: boolean; } Compon ...

Is there a way to set the initial value of an input's ngmodel variable using only HTML?

Is there a way to assign an initial value of "1" to the variable named "some" using ngModel during initialization? *Update: I am specifically interested in how to achieve this using HTML only component.html : <input type="text" value="1" name="some" ...

Authentic property does not reveal its contents

Currently, I am utilizing Angular2 and my goal is to only display a component if a certain property is true. The issue arises when trying to show the <sci-company-form> element when the sci variable is set to true. When setting public sci: boolean = ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

Are you interested in verifying the user's login status on the website using a Chrome extension?

My latest project involves creating a chrome extension using angular for a PHP website. Currently, the extension is working smoothly. It features a button that I would like to have the ability to enable or disable based on whether the user is logged in o ...

Converting JSON to TypeScript with Angular Casting

I'm facing an issue detailed below. API: "Data": [ { "Id": 90110, "Name": "John", "Surname": "Doe", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472d282f2923282207202a262e2b ...