Challenges with variable scopes and passing variables in Ionic 2 (Typescript)

In my Ionic 2 TypeScript file, I am facing an issue with setting the value of a variable from another method. When I close the modal, I get undefined as the value.

I'm encountering difficulty in setting the value for coord.

export class RegisterMapPage {

      ..necessary variables declared here..
      public coord: any;

      constructor(
            ....
      ) {}

      ionViewDidLoad() {
            this.initMap()
      }

      initMap() {
            this.geolocation.getCurrentPosition().then((position) => {

                  // // // ..... All map-related code goes here....

                  google.maps.event.addListener(marker, 'dragend', function () {
                        this.coord = marker.getPosition().lat() + ', ' + marker.getPosition().lng();
                        console.log(this.coord); // prints perfectly at this point.
                  });

            }, (err) => {
                  console.log(err);
            });
      }

      chooseCoord() {
            console.log(this.coord); // why is it undefined??
            this.viewCtrl.dismiss(this.coords);
      }

}

Even though I update the variable value of coord during the marker drag event, it shows up as undefined when I try to print it out. Can someone assist me with fixing this issue?

Thank you.

Answer №1

When you use the this inside your callback function, it does not refer to the instance of RegisterMapPage because you are utilizing the traditional function() {} syntax for the callback. To ensure that the context is correct, switch to using an arrow function:

google.maps.event.addListener(marker, 'dragend', () => {
    this.coord = marker.getPosition().lat() + ', ' + marker.getPosition().lng(); // The `this` now points to the `RegisterMapPage` instance since arrow function is used
    console.log(this.coord); // It will print correctly here.
});

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

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

Include images in the form of .png files within the td elements of a table that is dynamically generated in the index

I have successfully created a table using embedded JavaScript with the help of messerbill. Here is the code: <table id="Table1"> <tr> <th>Kickoff</th> <th>Status</th> <th>Country</th> < ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

How to Properly Convert a Fetch Promise into an Observable in Ionic 5 using Typescript?

I'm in the process of transitioning my Ionic3 app to Ionic5 and currently working on integrating my http requests. I previously utilized angular/http in Ionic3, but it appears that it has been deprecated. This was how I handled observables in my code: ...

Changing the text during a reset process

I've been grappling with this issue, but it seems to slip through my fingers every time. I can't quite put my finger on what's missing. My project involves clicking an image to trigger a translate effect and display a text description. The ...

What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router. An error consistently arises ind ...

React - CSS Transition resembling a flip of a book page

As I delve into more advanced topics in my journey of learning React and Front Web Dev, I discovered the ReactCSSTransitionGroup but learned that it is no longer maintained so we now use CSSTransitionGroup. I decided to create a small side project to expe ...

ways to eliminate attributes using mapped types in TypeScript

Check out this code snippet: class A { x = 0; y = 0; visible = false; render() { } } type RemoveProperties<T> = { readonly [P in keyof T]: T[P] extends Function ? T[P] : never//; }; var a = new A() as RemoveProperties< ...

The module declaration is triggering a lint error that reads "Unexpected token, expecting '{'"

To address the absence of available types for a library, I created the file omnivore.d.ts in TypeScript. Within this file, I added the following line: declare module '@mapbox/leaflet-omnivore' Upon running vue-cli-service lint in my project, an ...

Troubleshooting issue with alignment in Material UI using Typescript

<Grid item xs={12} align="center"> is causing an issue for me No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | GridSize>> & { ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

When using a function as a prop in a React component with Typescript generics, the type of the argument becomes unknown

React version 15 or 18. Typescript version 4.9.5. When only providing the argument for getData without using it, a generic check error occurs; The first MyComponent is correct as the argument of getData is empty; The second MyComponent is incorrect as t ...

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...

Tips for implementing event.preventDefault() with functions that require arguments

Here is a code snippet that I'm working with: const upListCandy = (candy) => { /* How can I add event.preventDefault() to make it work properly? */ axios.post("example.com", { candyName: candy.name }).then().ca ...

Php file not receiving data from ajax post method

forget.php PHP: if (! (empty($_POST['emailforget'])) ) { echo "here in the function"; } else { echo "here"; } AJAX: $("#passreset").on('click', function(e) { var emailforget = $("#tempemail").val(); alert(emailforget); ...

Implementing form validation for dropdown lists with Material-UI React: A comprehensive guide

I'm still learning React and I've been using material-ui for form validation. Everything was going smoothly until I encountered an issue with validating a dropdown list. Whenever I try to validate it, an error occurs: "Cannot read property ' ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...

JS Executing functions in a pop-up window

Recently, I have been immersing myself in learning JS and experimenting with webpage interactions. It started with scraping data, but now I am also venturing into performing actions on specific webpages. For example, there is a webpage that features a butt ...

Closing the Material UI dialog from an inner component

In my application, I have implemented a sign-in dialog using Material UI. However, I have separated the login button into its own component. I am trying to figure out how to close the dialog when the submit button in the SigninForm component is clicked. I ...