Using TypeScript to access global variables from inside a method

Hi everyone, I'm trying to figure out how to access variables from the global scope (this) within 2 methods. Any help would be greatly appreciated.

location: any;

    doSomethingOne() {
    Geolocation.getCurrentPosition().then((resp) => {
                this.location = resp;
                this.doSomething();

            }).catch((error) => {
                console.log('Error getting location', error);
            });
    }

    doSomething() {
        return new Promise(resolve => {
        this.http.get('http://xxxxxxxxx.xxxx/api/' + this.location.coords.latitude + '/' + this.location.coords.longitude + '/5')
            .map(res => res.json())
            .subscribe(data => {
                this.data = data;
                resolve(this.data);
            });
    });
    }

I'm struggling with accessing this.location from within a Promise. The console keeps showing 'undefined' when I try to access it. Can anyone help me out?

Answer №1

give this a shot

performTask(): Observalbe<any> {
    Geolocation.getCurrentPosition().then((resp) => {
                 return new Promise(resolve => {
        return this.http.get('http://xxxxxxxxx.xxxx/api/' + resp.coords.latitude + '/' + resp.coords.longitude + '/5')
            .map(res => res.json())
            .subscribe(data => {
                this.data = data;
                return resolve(this.data);
            });
        });

            }).catch((error) => {
                console.log('Error getting location', error);
            });
    }

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

Plot the components of an array and calculate the instances that JavaScript executes

I have an array containing information about PDF files stored in a buffer. Let's imagine this array holds ten PDF files structured like this: [{ correlative: "G-22-1-06", content: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 d3 eb e9 e1 0a ...

Issues with displaying data in Angular Material table

I am having trouble displaying data in a table. The data shows up when I display it in another element, but not in the table. Here is my code: <mat-accordion *ngIf="posts.length > 0"> <mat-expansion-panel *ngFor="let post of p ...

Unlock the power of Angular Component methods even when outside the Angular library with the help of @ViewChild()

In my Angular library, there is a component called AComponent which has its own template, methods, and properties. Once the Angular library is packaged, it becomes available as a NuGet package for other projects to utilize. @Component({ selector: ' ...

Instead of being viewed in the browser, the CSV file is being downloaded

I'm currently using Jhipster and have a function generated by Jhipster to open files in the browser. However, I'm facing an issue with this function when it comes to opening CSV files - instead of opening in the browser, they are being downloaded ...

Performing DTO validation in the controller before passing data to the service

My current challenge involves implementing validation in a PUT request to update data stored in MongoDB: DTO: export enum reportFields { 'startDate', 'targetDateOfCompletion', 'duration', } export class updateS ...

Problems encountered when utilizing $in operator in Mikro ORM MongoDB operations

For my project, I'm utilizing mikro orm with MongoDB to handle database operations in TypeScript. So far, it has proven to be the most effective ORM for MongoDB in this language. However, I've encountered type errors when using $in with Object ID ...

"Troubleshooting Angular 2 Directives That Cause Errors

Hey there, I'm currently working on understanding ANGULAR 2 routing, but I've encountered an error that's causing some trouble. Here's the issue I'm facing: app/app.component.ts(7,12): error TS2345: Argument of type '{ s ...

Assignment of type 'Object' is incompatible with type in new HttpClient / HttpGetModule implementation within Angular

After following the angular tutorial, I decided to test out the new httpClient.Get method. However, it seems that no matter what, it always returns results of type Object. // HttpClient getHeroes2 () { this.http.get<Hero[]>(this.heroesUrl) ...

Custom JSX element failing to include children during addition

I have created a unique component in JSX, like this: const CustomComponent = ({content}) => { return <div className={content}></div>; } I am using it as follows: <CustomComponent content={"xyz"}> <p>Some additio ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

I encountered an issue with Cypress when attempting to utilize a custom command. The error message "TypeError cy.login is not a function" keeps popping up. Any suggestions on how to resolve this

I am currently working on a TypeScript project and I am attempting to write some tests using Cypress. However, I encountered the following error: TypeError - cy.login is not a function. This error occurred during a before each hook, so we are skipping the ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...

Implementing Angular 4 to fetch information from a JSON file

As a beginner in Angular, my current task involves loading data from a JSON file upon click, which I have successfully achieved so far. However, I am facing an issue where I'm unable to load the first JSON object before clicking, meaning that I want ...

How to smoothly transition a div from one location to another using animations in an Ionic3-Angular4 application

I'm attempting to incorporate some animation into my Ionic 3 mobile app. Specifically, I want to shift a div from one location to another. In the code snippet provided below, I am looking to move the div with the "upper" class after the timeline-item ...

When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected. import 'reflect-metadata' function logType(target : any, key : string) { var t = Reflect.getMetadata("design:type", target, key); console.log(`${k ...

Issues with Injectable Service within Another Service in Angular 2

Having a problem with injecting a service into another service. I have a ContactService that retrieves data from the server using the handleError method, and an AlertService that handles errors thrown from the handleError method. Both services are declared ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

Exploring PrimeNG's method for expanding and collapsing groups

I'm attempting to incorporate two buttons that can be used to either expand or collapse all the groups in my code utilizing primeNG. Below is the functioning code: PLUNKER <p-dataTable [value]="data" sortField="room" rowGroupMode="subheader" grou ...

Enhancing Angular2 Routing with Angular4 UrlSerializer for Seamless HATEOAS Link Integration

As a newcomer to Angular4, I am currently exploring how to consume a HATEOAS API. My goal is to either pass an object that contains the self reference or the self reference link itself through the routing mechanism (for example, by clicking on an edit link ...

The TypeScript class for Date has a property that outputs a string

In my TypeScript code, I have defined a model class as follows: export class Season { ID: number; Start: Date; } Below is an example of how this model class is utilized within a component: export class SeasonsComponent { seasons: Season[]; sele ...