Ionic application encountering 'push' property error in MQTT only when used within an if statement

Being new to Ionic and MQTT, I could really use some help with an issue I am facing. In my development environment of Ionic CLI PRO 4.3.1, I am attempting to navigate to a new page when a message is received from an MQTT topic. However, I am encountering an error stating 'Cannot read property 'push' of undefined' when trying to execute the navCtrl statement within an if statement.

Here is a snippet of my code:

add-device.ts

import { Component } from '@angular/core';
import { IonicPage, ModalController, NavParams, NavController, ViewController } from 'ionic-angular';
import {Paho} from 'ng2-mqtt/mqttws31';
import { SignupPage } from '../pages';


@IonicPage()

@Component({
  selector: 'page-add-device',
  templateUrl: 'add-device.html'
})


export class addDevicePage {

  hello: any;
  pushPage: any;
  params: Object;

  constructor(public navCtrl: NavController, 
    public modalCtrl: ModalController, 
    private viewCtrl: ViewController,
    public navParams: NavParams) {}

deviceIDsend() {

console.log("MQQT");
var mqttHost = 'broker.mqttdashboard.com';
var port = 8000; // port for above

this.client = new Paho.MQTT.Client
(mqttHost, port,
  "web_" + parseInt(Math.random() * 100, 10));// set callback handlers
    console.log("connecting to "+ mqttHost +" "+ port);

this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived;

this.client.connect({onSuccess:this.onConnect.bind(this)});}

onConnect(client) {
console.log("onConnect");

this.client.subscribe("/j/" +this.device_id);
this.message = new Paho.MQTT.Message(this.device_id);
this.message.destinationName = "/j/" +this.device_id;

console.log(this.device_id);
 this.client.send(this.message);}

onMessageArrived(message) {
  console.log("onMessageArrived:" + message.payloadString);

  if (message.payloadString == "1") {
             console.log('in');

    this.navCtrl.push('SignupPage');  
   }

   else{
        console.log('hello');
   }
}

onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:" + responseObject.errorMessage);
  }

}


}

add-device.html

<ion-header transparent>
  <ion-navbar transparent>
  </ion-navbar>

</ion-header>
<ion-content class="background">
<ion-card>
  <form (submit)="deviceIDsend()">
  <ion-list>
        <h3 text-wrap style="padding-left: 8%">{{ 'j' | translate }}</h3>
        <p  text-wrap style="padding-left: 8%">{{ 'j' | translate }}</p>
      <div padding>
         <ion-item class="item3"> 
        <ion-label fixed>{{ 'NUMBER' | translate }}</ion-label>
        <ion-input type="email" type="text" name="deviceID" [(ngModel)]="device_id"></ion-input>
      </ion-item>
</div>
    <div padding>
        <button class="LoginButton" ion-button block value="submit" 
        [navPush]="pushPage">{{ 'ADD' | translate }}</button>
      </div>
      </ion-list>
  </form>
</ion-card>

</ion-content>

add-device.module

import { NgModule } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { IonicPageModule } from 'ionic-angular';

import { addDevicePage } from './add-device';

@NgModule({
  declarations: [
    addDevicePage,
  ],
  imports: [
    IonicPageModule.forChild(addDevicePage),
    TranslateModule.forChild()
  ],
  exports: [
    addDevicePage
  ]
})
export class addDevicePageModule { }

Answer №1

Have you considered using the arrow function syntax? I believe the issue may lie with this, although there seems to be some confusion as the original poster mentions that this.navCtrl.push functions correctly outside of the if statement.

onMessageArrived = (message) => {
  console.log("onMessageArrived:" + message.payloadString);

  if (message.payloadString == "1") {
             console.log('in');

    this.navCtrl.push('SignupPage');  
   }

   else{
        console.log('hello');
   }
}

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

Guide on integrating a newly bought template into an Angular 6 and Bootstrap 4 application

Although I have years of experience as a backend developer, I am relatively new to frontend development. Lately, I have been immersing myself in learning Angular 6 and Bootstrap 4 for an upcoming project at work. After setting up a basic Angular 6 applica ...

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

The functionality of PrimeNg TabView does not support observables

I am facing an issue with the PrimeNG TabView tabs when trying to populate them with data fetched from the server using Observables. I have included a sample example here for reference: https://stackblitz.com/edit/primeng-nx7ryc?file=app%2Fapp.component.t ...

How can I showcase images from a server in Node.js to an Angular 2 application?

I am currently facing an issue while trying to display uploaded files from Angular 2 using ngx-uploader and storing them on the backend (nodejs/feathers) with multer. I am unable to access and display the files, specifically images for now, but ultimately ...

Angular has the feature of a right float button with *ngfor

I've successfully implemented a form using Reactive Forms in Angular. Currently, my form is displayed as follows: <div class="center" appMcard> <form [formGroup]="GroupRMPM_FG"> <div formArrayName="GroupId_Name" *ngFor="let ...

Underscore.js is failing to accurately filter out duplicates with _uniq

Currently, I am integrating underscorejs into my angular project to eliminate duplicate objects in an array. However, I have encountered an issue where only two string arrays are being kept at a time in biddingGroup. When someone else places a bid that is ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Having trouble getting this multi-select feature to function properly in Reactjs with Typescript? Let's figure out the solution together

I encountered an issue where I was unable to select multiple items due to a join error code "Property 'join' does not exist on type 'unknown'." in a .tsx file const DropdownMultiselect =()=> { return( <> ...

Searching for and removing array elements in Angular 2 using the IndexOf method

Hey there! I'm currently in the process of trying to remove a specific item from my array while working with Angular2 and Typescript. My goal is to identify the index based on the value provided. The array I am working with is initialized as follows. ...

Mastering the art of debugging feathersjs with typescript on VS Code

I am facing an issue while trying to debug a TypeScript project with FeathersJS using VSCode. Whenever I try to launch the program, I encounter the following error: "Cannot start the program '[project_path]/src/index.ts' as the corresponding J ...

Deactivating attribute inheritance / configuring component settings with script setup and Typescript

Is there a way to disable attribute inheritance for a component's options when using script setup syntax with Typescript in Vue 3? Here is the JavaScript code example: app.component('date-picker', { inheritAttrs: false, // [..] }) How ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

Struggling to display data from .ts files in a mat-table or any HTML file within Angular 2

application-service.ts @Injectable() export class ScanServeripsService { constructor( private http: HttpClient, private httpUtils: HttpUtilsService, public env: EnvService ) { } API_FILE_URL = this.env.apiUrl + '/ap ...

Having trouble looping through a Map object converted from a JSON in TypeScript/Angular

Having recently delved into the world of TypeScript and Angular with a strong background in Java and Kotlin, I encountered a puzzling issue while working on a class. export interface GeoData { allregions: Map<string, string>; } This class was d ...

Changing the selection in the Angular Mat-Select dropdown causes the dropdown's position to shift

Issue with dropdown position: The dropdown should display below the select element, but when selecting the second value, it appears on top of the select element. I have removed any relevant CSS to troubleshoot, but the problem persists. See screenshots for ...

The guidelines specified in the root `.eslintrc.json` file of an NX workspace do not carry over to the project-level `.eslintrc.json` file

In my main .eslintrc.json file, I have set up some rules. This file contains: { "root": true, "ignorePatterns": ["**/*"], "plugins": ["@nrwl/nx", "react", "@typescript-eslint", &qu ...

Is it possible for recursive type definitions to handle generics effectively?

I have identified what I believe to be a bug in Typescript and have submitted it as an issue here. Considering that this might not get resolved quickly, I am reaching out for suggestions. Does anyone know of a better solution or workaround than the one pro ...

What is the best way to time a Google Cloud Function to execute at the exact second?

In my attempt to schedule a cloud function using the Pub/Sub trigger method along with crontabs, I realized that it only provides granularity to the nearest minute. However, for my specific application - which involves working with trades at precise time ...

Adding a custom type to a selected option for the onChange event in React-Select can be done by modifying the

After creating a SelectBox component using react-select and applying onChange event to it, I encountered an issue. I wanted to include a type "SelectedItemType" to the selected option in the onChange event, but the property of onChange was defined as (prop ...

Combining Angular 2 with CORS and incorporating a Spring Boot Rest Controller integrated with Spring Security

My application was functioning correctly using angular2 for the front end and spring boot rest controller. However, after incorporating spring security, I encountered an issue where functions with parameters in the spring boot rest controller were not bein ...