Executing a function within the constructor in Angular 2/IONIC 2

I am new to Angular 2 and I have a question regarding invoking a child method from the current constructor.

Is it possible to call the getPosition method from the constructor? I attempted to do so, but encountered an exception stating "getPosition is not a function".

import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { Platform } from 'ionic-angular';
import { Q } from 'q';

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

export class HomePage {

  private map;

  constructor(public navCtrl: NavController, platform: Platform, public alertCtrl: AlertController) {    
    platform.ready().then(() => { 
      try {
        let div = document.getElementById("map_canvas");
        // Initialize the map view
        this.map = (<any>window).plugin.google.maps.Map.getMap(div);

        // Wait until the map is ready status.        
        this.map.addEventListener((<any>window).plugin.google.maps.event.MAP_READY, function() {
          this.getPosition().then(data => {
            let GOOGLE = new (<any>window).plugin.google.maps.LatLng(data.latitude, data.longitude);
            this.map.setCenter(GOOGLE);
          }).catch(err => {            
            alert(err);
          });
        });
      } catch(err) {
        alert(err);
      }     
    }).catch(err => {
      alert(err);
    });
  }


  getPosition() {
    let deferred = Q.defer();
    try {
      this.map.getMyLocation(location => {
        deferred.resolve( {
          latitude: location.latLng.lat,
          longitude: location.latLng.lng
        });
      }, err => {
        deferred.reject(err);              
      });

    } catch(err) {
      deferred.rejec(err);
    }
    return deferred.promise;    
  }

}

Answer №1

Modify,

// Wait until the map is ready status.
this.map.addEventListener((<any>window).plugin.google.maps.event.MAP_READY, ()=> {
          this.getPosition().then(data => {
            let GOOGLE = new (<any>window).plugin.google.maps.LatLng(data.latitude, data.longitude);
            this.map.setCenter(GOOGLE);
          }).catch(err => {            
            alert(err);
          });
        });

to

// Wait until the map is ready status.
this.map.addEventListener((<any>window).plugin.google.maps.event.MAP_READY, function() {
      this.getPosition().then(data => {
        let GOOGLE = new (<any>window).plugin.google.maps.LatLng(data.latitude, data.longitude);
        this.map.setCenter(GOOGLE);
      }).catch(err => {            
        alert(err);
      });
    });

because by using function instead of ()=> (fat arrow syntax), your this reference is to the function object within the .addEventListener section

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

Maintain the chosen month in every dropdown toggle div in angular 4

While displaying data using toggle options, I am facing an issue where if I click on a different month, all other greyed out headers are displaying the previously selected values. I am trying to figure out a way to keep the value under Selected month as i ...

When using useEffect in React, the handleKeyDown function is causing the output to double with each

Whenever a user inputs something, the output doubles each time, leading to a long loop after just a few inputs. Below is the code snippet: const [direction,setDirection] = useState(Array(1).fill(0)); const directions = ["botNorth","botEa ...

Error: The function nodemailer.createTransport is not defined or does not exist

I'm currently working on integrating nodemailer into my nodejs application for sending emails. Check out the code below: var express = require('express'); var nodemailer = require('node-mailer'); var app = express(); app.post(&a ...

The search and sorting functionality in jquery DataTables is malfunctioning

I am facing difficulties with sorting and filtering the datatable as none of the JS functions seem to be working properly. I have already included the necessary JS files. Here are some details: I am connecting to a database to retrieve data in JSON format. ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

Unexpected TypeScript issue: Unable to access the 'flags' property of an undefined entity

Upon creating a new project and running the serve command, I encountered the following error: ERROR in TypeError: Cannot read property 'flags' of undefined Node version: 12.14 NPM version: 6.13 Contents of package.json: { "name": "angular-t ...

Utilizing Laravel Blade traits within Javascript script: A step-by-step guide

I am utilizing Laravel traits that are able to convert numbers into a money-currency format. If I wish to use it within a Blade template, I simply call it like this: <td class="text-center"> @money($repayment->admnin) </td> However, I am f ...

How can I limit generic types to only be a specific subtype of another generic type?

Looking to create a data type that represents changes in an object. For instance: const test: SomeType = { a: 1, b: "foo" }; const changing1: Changing<SomeType> = { obj: test, was: { a: test.a }, now: { a: 3 ...

Steps for Disabling Autocomplete in a JSP Page

How can I prevent the browser from remembering the username and password on my JSP page after submitting the form? I've already tried using autocomplete=off in the JSP code. <form name="indexFrm" id="indexFrm" autocomplete="off" method="post"> ...

How can I prevent Chrome from constantly prompting for permission to access the camera?

I have been working on some HTML/JavaScript/WebRTC projects that involve using the webcam. Despite hosting the files from my local web server (127.0.0.1), Chrome always prompts me for permission to access the camera each time I reload the page. Is there a ...

Ways to dynamically adjust the interval using an Observable pipe

One way to approach this is by updating the intervalValue through a button click event. This value is dynamic and changes frequently. intervalValue: number; intervalValue: Observable<number>; // I also attempted using this method, but the interval ...

Embracing the power of Typescript with Node and Express?

While trying out the TypeScript Node Starter project from Microsoft, I found myself intrigued. Is it really possible to use TypeScript instead of Node on the server? There are a number of server-side tasks where TypeScript excels: - Building a web API ser ...

Error message encountered when utilizing the Three.js JSONLoader: "'onLoad is not a function'."

I'm currently working on setting up a simple scene with Three.js to display an imported mesh rotating. I pieced together a couple of examples from the Three.js documentation and ended up with the code below: var scene, camera, renderer; var geometry, ...

How to retrieve a list of routes using axios in a Vue project set up with Webpack

I have implemented the prerender-spa-plugin in my Vue Webpack Cli project following the documentation by registering the Plugin in webpack.prod.conf.js as shown below: ... plugins: [ ... new PrerenderSpaPlugin( path.join(__dirname, '../dist&a ...

When `console.log(enum)` is executed in Typescript and AngularJS, the result will be `undefined`

Below is the code snippet for the file that contains the enum: module mops { export enum Status { OK = 0, ROC = (1 << 0), LLA = (1 << 1), LOA = (1 << 2), HIA = (1 &l ...

A different approach to calling JavaScript functions

I have a method that populates an array. I would like to utilize it in this manner: arrayname.fill("First Array"); And not like this: arrayname = fill("First Array"); What approach should I take? function fillArray(name) { let newArray = ...

Step-by-step guide on fetching blog posts from a Ghost blog by utilizing the API in a Vue cli project

I'm currently working on my Vue cli project and I am trying to showcase all the posts from a Ghost blog using the API. Unfortunately, the example provided on the page is for a nuxt project. Once we have called the dependencies and authenticated with ...

Unable to retrieve shared schema from a different schema.graphql file within the context of schema stitching

In my project, I have a user schema defined in a file named userSchema.graphql; id: String! userName: String! email: String! password: String! } In addition to the user schema, I also have separate schema files for login and register functionalit ...

What is the best way to divide a string that contains n concatenated JSON strings in JavaScript or Node.js?

Imagine I receive the following string from a socket server (which is out of my control): {"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}} Because it contains 2 JSON strings, using ...

What is the best approach for extracting dynamically generated content from this particular website?

Looking to scrape data from this website Attempting to extract "timestamp" using Python and store it in a variable for customized parsing. Tried using scrapy for scraping the "timestamp", but faced limitations due to javascript-generated data not being s ...