Ways to retrieve class variables within a callback in Typescript

Here is the code I'm currently working with:

import {Page} from 'ionic-angular';
import {BLE} from 'ionic-native';

@Page({
  templateUrl: 'build/pages/list/list.html'
})
export class ListPage { 
  devices: Array<{name:string, id: string}>;

  constructor() {  
    this.devices=[];       
  } 
  startScan (){
    this.devices = [];
    BLE.scan([],5).subscribe(
      (device)=>{        
        if(device.name){
          this.devices.push({name:device.name,id:device.id});
        }             
      },
      (err) => {
        console.log(JSON.stringify(err));
      }
      );
  }

  connectToDevice(device){
    BLE.connect(device.id).subscribe(success=>{
       console.log(JSON.stringify(success));
    });
  }
}

When I call the startScan function and try to add the returned device to an array, this.devices seems to be inaccessible. I attempted saving it using 'self=this', but that didn't work either. Can someone help me figure out what I'm missing?

UPDATE: Adding

var self = this;

at the beginning of startScan() and then utilizing it in the .subscribe callback solves the issue!

Answer №1

Sorry, this.devices is currently unavailable

A common problem that can be resolved by converting startScan to an arrow function:

startScan = () => {
    this.devices = [];
    BLE.scan([],5).subscribe(
      (device)=>{        
        if(device.name){
          this.devices.push({name:device.name,id:device.id});  // 'this.devices' does not exist
        }             
      },
      (err) => {
        console.log(JSON.stringify(err));
      }
      );
  }

For more information

Answer №2

This is the code snippet that allows you to add characters to an HTML textarea by clicking a button.

HTML

<div class="console-display">
<textarea [(ngModel)]="textAreaContent" name="mainText"></textarea>
    <div class="console-keys">
        <button (click)="getKeyInput($event)" name="key01" type="button" value="1">1</button>
        <button (click)="getKeyInput($event)" name="key02" type="button" value="2">2</button>
    </div>
</div>

TS

export class HomeComponent {
  tempString = "64";
  getKeyInput(event){
    let self = this;
    manageTextArea(self, event.target.value, this.textAreaContent);
  }
}

function manageTextArea(self , ch : string, textArea : string): void {
  if (checkCharacter_Number(ch)){
    self.textAreaContent += ch;
  }
  console.log(self.tempString);
}

The functionality works as intended.

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

Is it feasible to assess JavaScript expressions during compilation using Webpack?

I'm currently in the process of setting up webpack for a new project. This project is quite extensive and available in multiple languages. I am aiming to have each entry point in my project be represented by separate files in each language. The catch ...

Data has been successfully acquired through the query, however, it cannot be accessed via the GraphQL API

After successfully building the API with Apollo Server and verifying its functionality in GraphiQL, I proceeded to make requests to the API from a front-end React app using Apollo Client. const [getUserPosts, { loading, error, data }] = useLazyQuery(GET_US ...

script not found: typings-install

When running the command npm run typings-install, I encountered the following error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\n ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

The issue with linking to files on a custom 404 error page is that it doesn't function properly when

Having some trouble with my 404 page. I seem to have figured out the issue. The following URL works fine: sia.github.io/404.html and so does this one: sia.github.io/ooofdfsdfaablahblah However, when navigating to sia.github.io/1/2/3/, everything seems to ...

Calculating the number of digits in a series of numbers, experiencing a timeout issue (What is the page count of a book? from codewars)

Solving the Digits in a Book Problem Find the number of pages in a book based on its summary. For example, if the input summary is 25, then the output should be n=17. This means that the numbers 1 to 17 have a total of 25 digits: 123456789101112131415161 ...

Why is it that in React the render method is automatically bound to the component instance, while custom methods are not provided

Why is the render method automatically bound to the component instance in a class, but custom methods such as event handlers are not? I realize that using the bind keyword can make these event handlers work, but I'm curious to know why "this" can be ...

Secure your API routes in NextJS by using Passport: req.user is not defined

Currently, I am utilizing NextJS for server-side rendering and looking to secure certain "admin" pages where CRUD operations on my DB can be performed. After successfully implementing authentication on my website using passport and next-connect based on a ...

The challenge of generics in Typescript: destructuring and spreading

I am facing an issue with destructing parameters and creating a new object of the same type in Typescript. The following code functions properly: function customFunc<T extends { attribute: string }>(parameter: T): T { const { ...rest } = paramete ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Leveraging jquery's setInterval for automating tasks like a cronjob

I've been experimenting with Cronjobs and I've run into a roadblock. My goal is to have the cronjob execute every X minutes, containing a script with JavaScript that calls an ajax request every second for the next 60 seconds. The ajax call trigge ...

Merge the variables extracted from an array of objects

I need to extract specific data from an array of objects and perform a calculation. For example, the provided data is as follows: const item = [{ "act": "Q", "line": 1, &quo ...

Tips on attaching a class to elements in a loop when a click event occurs

In my HTML, I am displaying information boxes from an array of objects that are selectable. To achieve this, I bind a class on the click event. However, since I am retrieving the elements through a v-for loop, when I select one box, the class gets bound to ...

Managing form submissions in React with inputs spread across multiple components

I've been working on a ReactJS project with a form that is divided into multiple components. The main component imports all the child components, each containing input boxes, along with a submit button: My issue lies in trying to get all the componen ...

retrieve HTML content by its ID stored in a variable

In my JavaScript code, I have a variable named "value" that contains HTML data. I am trying to extract the data from a specific ID that is located within the element with ID #myDiv. var value="<div > <p class="">Hi <a href="/ ...

"Exploring the magic of Vue.js and Three.js: A guide to seamlessly changing CSS style elements within an

I'm currently in the process of converting my Three.js project to Vue.js Within my Three.js scene, I have a 3D model with HTML points of interest attached to it. It is crucial that these points remain fixed to the model and consistently face the cam ...

Having trouble getting the installed datejs typings to work properly

As I delve into Typescript due to my interest in Angular 2, I have come across the datejs Javascript library. To incorporate it into my Angular 2 project, I went ahead and installed datejs via npm, ensuring that it is correctly listed in my package.json. A ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

Modify the color of an Ionic button for a single button, rather than changing the color for all buttons

How can I modify this code so that only the clicked button changes its color, not all of them? Here is the current code: .html: <ion-col size="6" *ngFor="let data of dataArray" > <ion-card> <ion-card-header> ...

What are the steps for implementing videojs vr in a Vue.js project?

After installing the videojs vr with npm install --save videojs-vr, I attempted to use it in my project: https://i.stack.imgur.com/lSOqF.png However, I encountered this error message: https://i.stack.imgur.com/QSe1g.png Any assistance would be greatly ...