The values of the data members remain static within the Typescript environment

In my Ionic 2 project, I have a class structured like the one below. Instead of using the Ionic Native geolocation plugin, I am working with the locationServices plugin.

export class LocationManager{
   locationAcquiring:boolean;   
   locationAvailable:boolean;
   constructor(){
        this.locationAcquiring=true;
        this.locationAvailable=false;
   }            
   updateLocation(){
        //Utilizing certain Cordova plugins to store latitude and longitude in local storage variables.
        let self=this;
        cordova.plugins.diagnostic.isLocationEnabled(function(enabled){                                    
            let selfA=self;
            cordova.plugins.diagnostic.isLocationAvailable(function(available){
                let selfB=selfA;
                cordova.plugins.locationServices.geolocation.watchPosition(function(position) {
                    //Even though the project compiles without errors, the variable values are not getting updated here.
                    selfB.locationAcquiring=false;
                    selfB.locationAvailable=true;
                },function(error){});
            },function(error){});
        },function(error){});
    }
   displayLocationValues(){
        console.log(this.locationAcquiring);
        console.log(this.locationAvailable);
    }
}

The changes made within the locationServices plugin do not seem to reflect on the class variables.

Result from the displayLocationValues() function:

true
false

Answer №1

To simplify your code, you can now use TypeScript's lambda syntax () => {} instead of the let self = this; technique to access this within your lambdas in the context of class "a."

Make sure to check for errors during Cordova plugin calls by outputting them to the debug console. This could explain why your success callback code is not running.

Give this updated code a try:

export class a{
  location_acquiring: boolean = true;
  location_available: boolean = false;

  fun(){
    cordova.plugins.diagnostic.isLocationEnabled((enabled) => {
        cordova.plugins.diagnostic.isLocationAvailable((available) => {
            cordova.plugins.locationServices.geolocation.watchPosition(function(position) {
                this.location_acquiring=false;
                this.location_available=true;
            }, function(error){
              console.error('[watchPosition]', error);
            });
        }, (error) => {
          console.error('[isLocationAvailable]', error);
        });
    }, (error) => {
      console.error('[isLocationEnabled]', error);
    });
  }

  show_values(){
    console.log(this.location_acquiring);
    console.log(this.location_available);
  }
}

Hopefully, this update will resolve your issue.

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

Facing issues with Angular 6: encountering errors related to the module "rxjs/add/operator/map" and receiving another error indicating that 'map' does not exist on type 'Observable<Response>'

Currently in my Angular 6 project, I encountered two errors: ERROR in ./src/app/app/img/img.service.ts Module not found: Error: Unable to locate 'rxjs/add/operator/map' in '/Users/user/Projects/A4/imageSearch/src/app/app/img' ERRO ...

What are some ways to expand the width of a MaterialUI form control if no value has been chosen?

I am currently working on a project where I need a dropdown menu component with specific selections. However, the layout appears to be cramped and I'm struggling to adjust the width. Additionally, I've been unsuccessful in changing the font size ...

Adjust the class of a component

This is the HTML code for my home component: <button (click)="onClick('Hello')" [ngClass]="{'positive': connectedToWWE, 'negative' : !connectedToWWE}"> Hello! Click Me! </button> This is the Ty ...

Initiating the node js service locally

I have been working on a Node.js and Gradle application, but I'm having trouble figuring out how to run it locally. So far, I've done the Gradle build (./gradlew) and NPM run build (compile), with all my dependencies neatly stored in the node_mo ...

Issue with ngx-extended-pdf-viewer when using URL

I'm struggling to display my PDF file on a viewer using a URL in TypeScript. I am utilizing ngx-extended-pdf-viewer. Below is a snippet of my code with the URL replaced: <ngx-extended-pdf-viewer *ngIf="!isFirefox" [src]="'http://www.chi ...

`ng-apexcharts` causing unit test failures

I've been working on integrating apexcharts and ng-apexcharts into my home component. While I was able to get it up and running smoothly, it seems to be causing issues with my unit tests. Despite researching possible solutions, I haven't been abl ...

Learn to extract metadata from a gRPC service function using Node.js

Currently, my gRPC service is up and running with the following setup: server.addService(PassportService, implementation); server.bind(mfeConfig().grpc.passport, grpc.ServerCredentials.createInsecure()); server.start(); To call this service from a client ...

`The enforcement of a function's parameter requiring it to be part of the generic type T`

Is there a way in my typescript function to ensure that all keys in the second argument belong to the object defined by the first argument? For example: mapTo([new KeyValue('a', 'b'), new KeyValue('x', 'y')], {key ...

Creating a <p-table> with a sleek grey header

Trying to figure out how to make the table header grey in an Angular p-table. I have been using ng-template, but it seems like I might be missing something. Here's what I have: <p-table> <ng-template pTemplate="header" let-rowDat ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Personalizing Mat-Select Dimension - Angular 11

As a newcomer to Angular/Angular Material, I'm unsure if I need to write this code myself or if it's already predefined in a certain manner. The issue I'm experiencing is with the dropdown of the mat-select. The panel that appears when you c ...

Creating a subclass of `Error` leads to the error message "only refers to a type, but is being used as a value here."

I currently have Typescript 4.0.2 installed. Within lib.es5.d.ts, there is the snippet provided below: interface Error { name: string; message: string; stack?: string; } interface ErrorConstructor { new(message?: string): Error; (messa ...

Postpone the NgModule declaration by importing the module asynchronously

I am facing a challenge in dynamically importing a third-party module and then checking if it exists. The decision to declare it in the NgModule depends on its existence (true/false). Below is an example of my code. However, the issue arises because the ...

Utilizing Typescript with Angular CLI and Express/Node concurrently in a project: A Comprehensive Guide

Currently, I am in the process of creating a basic MEAN project structure with the Angular CLI. Here, you can find an overview of the folder setup along with the tsconfig.json file. https://i.sstatic.net/VvPpU.jpg Presently, the server code resides in th ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

How to Manually Update the Angular Release Version in your environment.ts File using the CLI

Within the environment.ts file, we store the release version. I am looking for a command to increment the minor version from the Command Line Interface (CLI) in order to use it within a Jenkins build job. export const environment = { … version: ' ...

Issue with throttle function not properly handling the class method call

I am facing a challenge with my code where I am trying to throttle text input, but it seems that calling another method is causing the throttling to not work as expected. import { throttle } from 'lodash'; ... <input type="t ...

Guide to updating the content of an input field

As a newcomer hobbyist, I'm attempting to automate my web browsing experience. My goal is to have the browser automatically fill in my username and password, and then click the sign-in button using a combination of JavaScript and Tampermonkey. This me ...

Organizing a store in a hierarchical structure

I am currently facing an issue with creating a hierarchical store in Angular. My goal is to have multiple reducers that work on specific parts of the application. Here's the scenario: I am working on an HR application that has a talent (employee) mod ...

Retrieving information as the user navigates to the next page

Currently, I am using an API endpoint that retrieves over 1000 data objects and delivers them to the user. I believe this method is not efficient since only 30 objects are displayed at once. Is there a more efficient way to load these objects, perhaps in ...