I am struggling to convert my class into a promise within Ionic2

After running the getLocalPosition() function and attempting to set my Position class variable inside it, I encountered the following error.

TypeError: Cannot read property 'setLat' of null
    at VM11086 main.js:52673
    at t.invoke (VM11035 polyfills.js:3)
    at Object.onInvoke (VM11086 main.js:34675)
    at t.invoke (VM11035 polyfills.js:3)
    at e.run (VM11035 polyfills.js:3)
    at VM11035 polyfills.js:3
    at t.invokeTask (VM11035 polyfills.js:3)
    at Object.onInvokeTask (VM11086 main.js:34666)
    at t.invokeTask (VM11035 polyfills.js:3)
    at e.runTask (VM11035 polyfills.js:3)
VM11086 main.js:52685 TypeError: Cannot read property 'setLon' of null
    at VM11086 main.js:52681
    at t.invoke (VM11035 polyfills.js:3)
    at Object.onInvoke (VM11086 main.js:34675)
    at t.invoke (VM11035 polyfills.js:3)
    at e.run (VM11035 polyfills.js:3)
    at VM11035 polyfills.js:3
    at t.invokeTask (VM11035 polyfills.js:3)
    at Object.onInvokeTask (VM11086 main.js:34666)
    at t.invokeTask (VM11035 polyfills.js:3)
    at e.runTask (VM11035 polyfills.js:3)

However, setting the class in the constructor seems to work without any issues.

Here is the .ts code snippet:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import { Storage } from '@ionic/storage';
import { Position } from './clases';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  private position = new Position();

  constructor(public navCtrl: NavController, public storage: Storage) {
    this.position.setLat(1234311);
    console.log(this.position);
    // Or to get a key/value pair
    this.storage.get('position').then((val) => {
      this.position = val;
    }).catch((err) => {
      console.log(err);
    });
  }
  getLocalPosition() {
    Geolocation.getCurrentPosition().then((resp => {

      try {
        this.position.setLat(resp.coords.latitude);
      } catch (e) {
        if (e instanceof TypeError) {
          console.log(e);

        }
      }
      try {
        this.position.setLon(resp.coords.longitude);
      } catch (e) {
        if (e instanceof TypeError) {
          console.log(e);

        }
      }

      //this.storage.set('position', this.position);
    }))
  }


}

And here is the class definition:

export class Position {
    private lat: number;
    private lon: number;

    constructor(lat: number = 0, lon: number = 0) {
        this.lat = lat;
        this.lon = lon;

    }
    setLat(lat: number) {
        this.lat = lat;
    }
    setLon(lon: number) {
        this.lon = lon;
    }
    getLat() {
        return this.lat;
    }
    getLon() {
        return this.lon;
    }

    getPosition() {
        let position = {
            lat: this.lat,
            lon: this.lon
        }
        return position;
    }
}

Thank you for taking the time to review this.

Answer №1

There was an issue in the following line of code:

this.storage.get('position').then((val) => {
  this.position = val;
}).catch((err) => {
  console.log(err);
});

After setting `this.position` with `val`, I encountered a problem accessing the `setLat` method as it does not exist.

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

Performance issues arise in Angular when multiple DOM elements are added through dynamic components with binding, causing lagging

I have implemented a nested expand/collapse feature using dynamic components in Angular 5. Although the functionality works well, the browser crashes or the scroll stops working when loading multiple DOM elements (resulting in jerky scroll). This feature ...

Utilizing Filestack in Angular 2

I'm currently working on integrating image uploading functionality into my Angular 2 App, and I have decided to utilize Filestack (formerly filepicker.io) for storing the images. Following Filestack's recommendations, I added the necessary script ...

Show loading icon while resolving routes or changing routes

I am attempting to display a loading icon while the route resolver is fetching data from the database. Here is what I have tried: Main Component: _router.events.subscribe((routerEvent: RouterEvent) => { if (routerEvent instanceof NavigationStart) ...

Verify whether the object is properly implementing the interface

Design: export interface Person { id: number; firstName: string; lastName: string; age: number; } Is there a way to verify that an object returned from the backend aligns with the structure defined in the Person interface? ...

(IONIC 2) Issue: error when trying to integrate socket.io with express, receiving a 404 (Not Found) error when attempting to connect to http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LvraMV

I encountered an issue while attempting to connect my node server with Ionic2, Here is some background information: 1. I am developing the node server on my personal laptop. 2. When running 'ionic serve', everything functions normally without a ...

Creating a velocity gauge style graph in Angular 4: A step-by-step guide

Hello, I'm currently working on building a speedtest-inspired application. While everything else is going smoothly, I'm struggling to incorporate a speedometer-like chart in Angular 2/4. Despite searching extensively, I've only come across J ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

Unexpected field error is thrown by Multer in Node.js

I am currently utilizing Angular with ng2-file-upload, and I have encountered an error: { Error: Unexpected field at makeError (C:\Users\cDotsp27598345\Desktop\Projects\ZeoliteGlobal\node_modules\multer\lib\mak ...

Sending JSON RPC post requests in Angular 4

Attempting to retrieve JSON RPC data from the server using Angular 4 HttpClient. The error message received is {code: -32600, message: "INVALID_JSON_REQUEST: The JSON sent is not a valid JSON-RPC Request object"}. The command used is: curl -i -X POST -d ...

What is the best way to change between different Angular 2 material tabs using typescript?

I need help with switching tabs using buttons <md-tab-group> <md-tab label="Tab 1">Content 1</md-tab> <md-tab label="Tab 2">Content 2</md-tab> </md-tab-group> <button md-button (click)="showTab1()">Show Tab 1< ...

Is there a way to achieve a seamless compilation in TypeScript?

Hopefully this is straightforward! TypeScript Latest version: 1.9.0-dev.20160512 (can be installed using npm install -g typescript@next as suggested by @basarat) Node v5.11.0 Windows 10.0.10586 First file: u1c.ts import * as u1u from "./u1u.ts" let p = ...

The attribute 'photographs' is not defined within the category 'Image[]'

I'm attempting to retrieve a response from the Pexels API for images. My goal is to fill the empty defaultImages array within the photos object obtained from the response. import * as React from "react"; import { ChakraProvider} from "@ ...

I am unable to execute the command "npm run sample" within my project

After downloading the project, I encountered an error while trying to run it on my PC. Heading I am unsure about how to resolve this issue and would appreciate any guidance. The contents of my package.json file are as follows: { "name": "ng-contact-ma ...

The `ngx-infinite-scroll` feature does not function properly on mobile devices when used in conjunction with the

I'm currently working on an Angular project that utilizes the mat-sidenav layout and routing. I came across an issue when trying to display a list of elements from a database using ngx-infinite-scroll. Following the user guide for ngx-infinite-scroll, ...

Custom preflight in Angular HTTP interceptor is a powerful feature that allows

In my development project, I am creating an application that interacts with a backend API that mandates the inclusion of a XSRF-TOKEN header in every request. To comply with this requirement, I have implemented an HTTP interceptor as follows: intercept(req ...

Utilizing the power of d3.js within Angular 4

Currently, I have successfully implemented code to draw a polygon using the mouse in a normal JavaScript file. Now, I am looking to replicate the same functionality in my TypeScript file. Below is an excerpt from my d3.js file: //D3.JS VERSION 3 //------ ...

What is the recommended Angular version compatible with Node.js version 20.15.1?

After upgrading my node version from 14 to 20.15.1 and angular-cli from 17.3.8, I encountered a peer dependencies version mismatch error. How can I resolve this issue? I have already run npm i, updated all package versions in package.json, and deleted pa ...

mat-checkbox not displaying correct state when dynamic values are applied in an Angular project

Within my Angular application, I am utilizing mat-checkbox to showcase a collection of items accompanied by checkboxes. The values assigned to these checkboxes are dynamic and are configured through the [value] or [checked] input property within the mat-ch ...

How can one efficiently update post statuses in Ionic 4 without having to constantly reload or refresh the webpage?

I have created a dynamic list of posts, each with a "like" and a "comment" button. The issue I'm facing is that whenever I click on the like button, I have to manually refresh the page for the changes to appear. One approach I considered was incorpor ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...