Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file:

import { Component } from '@angular/core';
import * as mqtt from 'mqtt';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
 private client: mqtt.Client;
  ngOnInit(): void {
    this.initializeMQTTClient();
  }
  public initializeMQTTClient() {
    console.log('Attempting connection');
    this.client = mqtt.connect('ws://mqttBroker.de:1882');
    this.client.addListener('connect', this.onConnect);
    this.client.addListener('message', this.onMessage);
  }

  private onConnect() {
    console.log('Connected successfully');
    this.client.subscribe('/broker/response/clientID');
    this.client.publish('/providers', '{...Message...}');
  }

  private onMessage(args: any[]) {
    console.log(args[0]);
    console.log(args[1]);
  }
}

The connection is established successfully as I can see the 'connected' message in the log, but then I encounter an error

Cannot read property 'subscribe' of undefined

I am puzzled as to why the client variable is not accessible in the onConnect method. I believe there might be some fundamental TypeScript concept that I am missing, but despite my efforts, I haven't been able to pinpoint the exact issue.

Answer №1

The main issue lies in the binding of 'this' keyword (https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md). To resolve it, you can modify the code as follows:

this.client.addListener('connect', this.on_connect.bind(this));
this.client.addListener('message', this.on_message.bind(this));

Alternatively, you can also use arrow functions like this:

this.client.addListener('connect', () => {this.on_connect()});
this.client.addListener('message', (args) => {this.on_message(args)});

Answer №2

The issue you're facing is that the context of this has been altered within the on_connect message scope. This stems from how TypeScript manages the assignment of this when utilizing arrow notation, or lack thereof, in a callback function. Adjust your callback bindings as shown below:

this.client.addListener('connect', () => this.on_connect());
this.client.addListener('message', () => this.on_message());

Due to not using arrow notation in the original definition, TypeScript does not automatically handle the scope binding during Transpilation. Consequently, the this inside the on_connect function ends up referring to the function itself.

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

What measures can be taken to safeguard my web app from unauthorized devices attempting to connect?

I am looking for a way to restrict access to a webapp so that only authorized users can connect from approved computers or mobile devices. If a user enters the correct username and password, access will be granted only if they are using a device approved b ...

Angular 8 ngFor not displaying expected information from object

I have a set of data which includes IDs, versions, and user details for Paul and Peter. See below: var data = { id: 1 version: 1 user: [ { name: 'paul' }, { name: 'peter' ...

Compiling async code with generators in Typescript proves to be challenging

Scenario As I delve deeper into Typescript, I've come across the advice that blocking calls should not be made within asynchronous code. I have also found generators to be helpful in simplifying directory traversal and preventing stack overflow. ...

Retrieving currentUser data using Vue.js, Vuex, Express, and MongoDB

I am currently working on creating a MEVN stack authentication page that displays information about the user who is logged in. After successfully logging in, the router redirects to Home.vue and passes the username as a prop. The onSubmit method in Login. ...

There are no HTTP methods being exported in this specific file. Remember to export a named export for each individual HTTP method

Currently, I am working on a React.js/Next.js project that incorporates Google reCAPTCHA. The frontend appears to be functioning properly as I have implemented print statements throughout the code. However, I am encountering an error in the backend display ...

Using the TypeScript NextPage function along with the getInitialProps static method and @typescript-eslint/unbound-method

After enabling typescript-eslint with its recommended settings, I encountered an issue in my code. I came across this helpful post on Stack Overflow: Using getInitialProps in Next.js with TypeScript const X: NextPage = props => {/*...*/} X.getInitialP ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

Guide on exporting a reducer from a Node module built on React Redux

I am currently working on a project that requires importing a component from an external node module. Both the project and the component utilize React and Redux, and I intend for them to share the same store. Below is a snippet of the reducer code for the ...

JavaScript code to determine if a Rating is enabled for a SharePoint Online list

Currently, I am working on a JavaScript code that will allow users to provide star ratings for specific articles through a widget. One of the requirements is to first verify if the Rating feature is enabled for a particular SharePoint list. If it is enable ...

Is it possible to utilize ngIf to reuse a component when encountering a 404 error? How can the error be captured?

In my app-routin.module.ts file, I have a root component named HomeComponent that I reuse for unknown routes. const routes: Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { p ...

How can I generate a hyperlink for a specific directory on Github Pages?

If I have a repository with one file and one folder, as listed below: index.html folder The folder contains another file named: work.html My goal is to access the folder website using only the link: username.github.io/repositoryname/folder Instead ...

Unusual title attributed to saving the date in Firebase

Could anyone explain why my JSON appears like this https://i.stack.imgur.com/xzG6q.png Why does it have a strange name that starts with -M-yv... instead? I am saving my data using the http.post method, passing the URL to my database and an object to save ...

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

A simple guide on integrating personalized color palettes into Material-UI Theme

One enhancement I'd like to make in my theme is the inclusion of a custom color called warn import React from 'react' import { MuiThemeProvider } from '@material-ui/core/styles' import createMuiTheme from '@material-ui/core/s ...

What is the best way to retrieve a specific object from a JSON file using a Get request in a Node.js application?

My focus is on optimizing an API, which is why I'm working with only the data that's essential for my analysis. I've set up a route to extract specific objects, but I'm only interested in four of them: account_manager, fronter, closer, ...

Populate a PHP array with designated file types from a designated folder, to later be loaded into a JavaScript array

My goal is to populate a JavaScript array with files of type .dae from different directories: "/collada/basement", "/collada/ground", "/collada/first", and "/collada/roof". I'm thinking of creating separate arrays for each directory. I understand that ...

Disappear gradually within the click event function

I have a coding dilemma that I can't seem to solve. My code displays a question when clicked and also shows the answer for a set period of time. Everything works perfectly fine without the fadeOut function in the code. However, as soon as I add the fa ...

Differences in file sizes in Angular-CLI builds

After building my Angular app, I noticed the following output: Upon closer inspection, it is evident that 0.7f787ebcd865a23bb4ea.chunk.js and vendor.fbdfd024192bddab02d3.bundle.js are quite large. To confirm their sizes, I checked the actual file size us ...

Setting up Node on a Ubuntu system

Currently, I am in the process of installing Node.js to run my Angular2 program. However, I encountered an error during the installation: npm WARN npm npm does not support Node.js v0.10.25 npm WARN npm You should probably upgrade to a newer version of nod ...

Update the Material-UI theme to a personalized design

I am currently using Material-UI in my React project. However, I'm facing some difficulties in applying a theme globally. Up until now, I have only managed to apply the theme to individual components like this: import { MuiThemeProvider, createMuiTh ...