I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code:

import { Component } from '@angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { Paho } from 'ng2-mqtt/mqttws31';

@Component({
  selector: 'page-greywater',
  templateUrl: 'greywater.html'
})
export class MQTT_Greenchain {
  private _client: Paho.MQTT.Client;
  private options = {
    userName: 'rdjghvoh',
    password: 'w7Ex0VTqZViw',
    timeout: 30,
    useSSL:true,
    onSuccess:this.onConnected,
  };
  private topic: string;
  public displayedMessage: string;
  public mes: Paho.MQTT.Message;
  public constructor() {
    this._client = new Paho.MQTT.Client(
      "m20.cloudmqtt.com",
      Number(30775),
      "",
      "peter"
    );
    this._client.onConnectionLost = (responseObject: {errorCode: Number, errorMessage: string}) => {
      console.log('poes');
      console.log(responseObject.errorMessage);
    };

    this._client.onMessageArrived = (message: Paho.MQTT.Message) => {
      this.onMessageArr(message);
      console.log('Message arrived.');
    };
    this.topic = "haha";
    this.displayedMessage = "what I was";
  }
  connectMe() {
    console.log("MQTT OPTIONS: " + this.options);
    this._client.connect(this.options);
  }
  private onConnected(): void {
    console.log('Connected to broker.');
    this._client.subscribe(this.topic);
    this.mes = new Paho.MQTT.Message("-1"); // -1 => Notify
    this.mes.destinationName = this.topic;
    this._client.send(this.mes);
  }
  private onMessageArr(message: Paho.MQTT.Message){
    this.displayedMessage = message.payloadString;
  }
}

In Angular 1, I had no issues calling the following function and getting everything related to MQTT working. The Angular 1 function looks like this:

function onConnect() {
  sharedUtils.hideLoading();
  console.log("onConnect, CURRENT TOPIC: " + mqttData.currentTopic);
  client.subscribe(mqttData.currentTopic);
}

The argument in the above function, mqttData.currentTopic, is simply a string.

This function only accepts 1 argument even though it can technically accept 2 (an options object).

In Angular 2, TypeScript throws an error when I try to call the function with just one argument:

Supplied parameters do not match any signature of call target

Why does Angular 2 not allow me to call the function with only one argument as in Angular 1? When I provide {} as a second argument:

this._client.subscribe(this.topic, {});

I get the error:

AMQJS0005E Internal error. Error Message: Cannot read property 'subscribe' of undefined, Stack trace: TypeError: Cannot read property 'subscribe' of undefined

This error is received in the response object parameter passed to the onConnectionLost callback function.

Even though 'this._client' seems defined based on the console message 'Connected to broker.', where the onSuccess callback is evidently called, why am I encountering these issues?

What am I missing here?

Answer №1

Give this a shot and let me know if everything is running smoothly

this.client.subscribe(this.topic, '');

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

JQuery Accordion SubMenu/Nested Feature malfunctioning

I have successfully implemented a JQuery Accordion on my website and it is functioning properly, opening and closing as expected. However, I am facing an issue when trying to add a submenu within the accordion. The submenu does not work as intended and lac ...

Issues with the messaging functionality of socket.io

Utilizing socket.io and socket.io-client, I have set up a chat system for users and operators. The connections are established successfully, but I am encountering strange behavior when it comes to sending messages. For instance, when I send a message from ...

How to achieve a reverse slideToggle effect with jQuery when refreshing the page

After creating a custom menu on Wordpress using jQuery slideToggle to toggle dropdown on hover, everything seemed to be working perfectly. However, I noticed that when I refreshed the page while moving my cursor between two menu items with dropdown menus, ...

The element 'commit' cannot be found within the property

I am facing an issue when transitioning from using Vuex in JavaScript to TypeScript. The error message Property 'commit' does not exist appears in Vuex's mutations: const mutations = { methodA (): none { this.commit('methodB' ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Effortlessly Display or Conceal Numerous Table Columns Using jQuery

I have a small table where I want to hide certain details with a basic button... for instance, table { border-collapse: collapse; } th, td { border: 1px solid gray; padding: 5px 10px; } <button>Show/Hide Details</button> <table> ...

Error encountered: "Instance variable for Apex chart not defined while attempting to update charts with updateOptions."

I have integrated Apexcharts to create charts within my application. The initial data loads perfectly upon onload, but when applying a filter, I face an issue where the charts need to be refreshed or updated with the new filtered data. I attempted to use t ...

Guide on how to showcase an array in a string format using table rows in JavaScript or jQuery

After making an AJAX call to a PHP database, I receive a String as a result in my script. The format of the string is shown below: array(4) { [0]=> array(3) { ["id"]=> string(3) "181" ["number"]=> ...

Problem with clicking on items in Slick Slider Variable width menu once they reach the end

Is there a way to stop the slick slider with variable width items from scrolling after reaching the last item? I am encountering this issue where it continues to scroll even after the end. If you want to see the problem in action, check out this fiddle: h ...

Obtaining static images from the public directory with getStaticProps in Next.js

Next.js provides a thorough method for accessing images from the /public/ folder, where static assets are stored. This involves using Node's fs module and fetching them within the getStaticProps function. Here is an example: export async function get ...

Unable to display socket data in Angular js Table using ng-repeat

div(ng-controller="dashController") nav.navbar.navbar-expand-sm.navbar-dark.fixed-top .container img(src='../images/Dashboard.png', alt='logo', width='180px') ul.navbar-nav li.nav-item ...

Master the art of utilizing angular-filter

Encountering some challenges while attempting to utilize angular-filter: The following links have been imported into the HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src=" ...

AngularJS application: the button requires two clicks to activate

In my attempt to develop a simple CRUD app using AngularJS, I encountered an issue. The initial step involves clicking a button that fetches data from a REST API and populates an array. This array is then iterated using ng-repeat to generate Bootstrap card ...

Creating a type-safe method wrapper in TypeScript based on function names

Many Q&As discuss creating a function wrapper in TypeScript, but my question is how to do the same with named methods. I am interested in writing something similar to this JavaScript code: function wrap(API, fnName, fn) { const origFn = API.p ...

Changing Float Attributes to String in Google Earth Engine

I am trying to export data from Google Earth Engine to my Google Drive. To name the file, I am using information from its data properties which results in 2019.0_1.0. However, I would like the file name to be in a different format - '2019_1'. Bel ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

I keep receiving an error in Angular JS but I'm unsure of the reason

I've been working on AngularJS and created a basic module and controller. I'm attempting to show the data of an element inside the controller on the HTML view page, but all I see is {{student.name}} and I'm receiving an error message that sa ...

What is the maximum file size that the data link is able to store?

For instance, a file like an image, video, or sound can be saved in the data link Take an image for example, it may be stored with the initial link: data:image/jpeg;base64,/..... followed by various characters. But, is there a specified size limit at whic ...

Solving the Angular form glitch: error message not displaying

I am facing an issue with my simple form where I am not able to display errors related to the fields. <html lang="en" ng-app="MyApp"> <head></head> <body ng-controller="AppCtrl"> <form name="myForm" id="myForm"& ...

Having trouble with the "setValue" property being undefined error. Looking for a solution to input text into a codeMirror element using Selenium WebDriver with Java

Currently, I am attempting to input text into a textarea field that is recognized as CodeMirror. Below is the code snippet I have been working with: {... WebElement scriptField = this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span")); ...