Storing geolocation information in local variables for future use

I am completely new to Nativescript (with Angular 2/TypeScript). My goal is to utilize the Nativescript geolocation plugin to track a user's location and store the data (latitude and longitude) for future use. Here is a snippet of my code:

export class AppComponent {
    public latitude: number;
    public longitude: number;

 public constructor() 
 {
      this.updateLocation();
      this.getWeather(this.latitude ,this.longitude);
 }

private getDeviceLocation(): Promise<any> {
        return new Promise((resolve, reject) => {
            geolocation.enableLocationRequest().then(() => {
                geolocation.getCurrentLocation({desiredAccuracy:3,updateDistance:10,timeout: 20000}).then(location => {
                    resolve(location);

                }).catch(error => {
                    reject(error);
                });
            });
        });
    }

 public updateLocation() {
        this.getDeviceLocation().then(result => {
// saving data here for later use
            this.latitude = result.latitude;
            this.longitude = result.longitude;
        }, error => {
            console.error(error);
        });
    }

public getWeather(latitude:number,longitude:number){
// perform actions with latitude and longitude 
}
}

However, I am facing an issue where I cannot pass the values of latitude and longitude to the getWeather method. They are being received as undefined. What could be the reason for this? I am aware of a workaround by calling getWeather directly inside the updateLocation function where these values are available, but I feel like there might be a better way to handle this. Any help would be greatly appreciated.

Answer №1

Your perception of what is considered "not an appropriate way" may actually be the most appropriate solution in this case. The this.updateLocation() function operates asynchronously as a Promise, meaning that the line of code below it (

this.getWeather(this.latitude ,this.longitude)
) will execute before this.latitude and this.longitude are fully initialized.

In order to ensure that getWeather is called after proper initialization, you should wait for the Promise to resolve within the updateLocation function.

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

Execute a function when a button is pressed in a React application

Currently, I am dynamically generating some HTML and have a requirement for certain "events" to trigger an onclick function. The technology stack I am using for this project involves React and TypeScript. My initial approach is as follows: function add_ev ...

Attempting to create a function that removes the first and last characters from a string, however encountering issues with the code in TypeScript

Currently, I am delving into the world of TypeScript and facing a challenge. The task at hand involves creating a function that returns a string without its first and last character. Can anyone offer assistance with this problem? Below is the code along wi ...

Testing Angular components that have protected @Input properties

Typically, we designate variables as protected when they are only used within a component and its subclasses, but not in the template itself. This approach becomes particularly advantageous when a class contains multiple variables, as it makes it easy to ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...

Using the watch flag in TypeScript across multiple projects - A comprehensive guide

In my project, I have the following scripts section in the package.json: "watch": "?", "build": "npm run build:compactor && npm run build:generator && npm run build:cleaner", "build:lambda": ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Collaborate on an Angular2 codebase for both a web application and a hybrid application

I am considering creating a mobile app based on my existing Angular2 web app codebase. After researching, I have found two possible options - Ionic2 and NativeScript. Upon further investigation, it appears that both Ionic2 and NativeScript have their own ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

The parameter failed to initialize causing the HTTP service to fire prematurely

In my project, I am utilizing Angular 10. Within the ngOnInit function, I have nested HTTP calls structured like this: ngOnInit(): void { let communetyid; this.route.data.subscribe(data => { this.route.params.subscribe(params => { ...

I'm confused by the function: "sort((a: Article, b: Article) => b.votes - a.votes);"

I'm having trouble grasping the concept of the return statement in sortedArticles(). Can anyone provide me with a resource or explain how this sorting function works? sortedArticles(): Article[] { return this.articles.sort((a: Article, b: Article ...

Is there a way to enforce a mandatory lambda argument?

I am trying to pass a lambda into a function, but I need the lambda to have only one argument. TypeScript correctly generates an error if I provide two parameters to the lambda, however it does not raise any issues if I leave out any arguments altogether ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

Declaratively assign ambient typings to an unfamiliar object in Typescript

I am facing an issue with an external library named "gapi" that is set to a property on the window object as window.gapi. I would like to keep it there while using the @types/gapi declaration. Is there a way to achieve this, like the following code snippet ...

Next.js is perplexing me by throwing an error about Event handlers not being able to be passed to Client Component props, even though the component clearly has "use client" at

My bundler generates a basic React component like this "use client"; "use strict";var a=Object.create;var r=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,s=Objec ...

How can I iterate over nested objects using ngFor in Angular HTML?

We have a data object stored on our server structured like this; { "NFL": { "link": "https://www.nfl.com/", "ticketPrice": 75 }, "MLB": { "link": "https:// ...

What is the best way to test multiple store injections withLatestFrom in NgRx Effects?

Within our angular web application, we have implemented NgRx-effects that rely on various data sources within our store. To achieve this, we have adopted the suggested withLatestFrom strategy: withLatestFrom( this.store.pipe(select(...)), this.store ...

Bundle multiple internal modules in typescript for easy exporting

Currently, I am exploring the idea of implementing TypeScript in node.js. I have been accustomed to using TypeScript with the ///<reference.../> syntax for internal modules. However, as projects grow larger, managing interlinking references between m ...

TypeScript - The key is missing from the type definition, yet it is present in reality

I'm currently working on developing my own XML builder using TypeScript, but I've run into a significant issue: Property 'children' does not exist in type 'XMLNode'. Property 'children' does not exist in type &apos ...

Having trouble importing a file in TypeScript?

I needed to utilize a typescript function from another file, but I encountered an issue: I created a file called Module.ts with the following code snippet: export function CustomDirective(): ng.IDirective { var directive: ng.IDirective = <ng.IDire ...

Creating a subtype in typescript involves specifying values for certain fields and getting rid of any optional members in the type definition

interface Person{ name:string, age:number, gender?:string } interface Employee extends Person{ name='John Doe', age:number } I am trying to achieve the above structure for a person and employee in TypeScript. I am also curious if something simi ...