Acquired this as empty

I encountered a strange error message saying "this is null" and I can't figure out what the issue is. Here is my demo on Stackblitz.com with an example code for your reference.

Component

ngOnInit() {
    this.getCurrentLocation();
  }

  getCurrentLocation() {
   navigator.geolocation.getCurrentPosition(position =>{
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.weatherInfo(this.lat, this.lng)
},function(){
       this.origin = { lat: '3.140853', lng: '2.693207'};
       console.log(this.origin)
       this.weatherInfo(this.origin.lat, this.origin.lng)
})



  }
  weatherInfo(lat, lng){
    console.log(lat, lng);
  }

Answer №1

Ensure to utilize an arrow function (() => { rather than function() {) as it is necessary for the specific scope:

getCurrentLocation() {
   navigator.geolocation.getCurrentPosition(position =>{
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.weatherInfo(this.lat, this.lng)
}, () => { // At this point
       this.origin = { lat: '3.140853', lng: '2.693207'};
       console.log(this.origin)
       this.weatherInfo(this.origin.lat, this.origin.lng)
})

You may find value in reading: Understanding "this" in javascript with arrow functions or Arrow functions and the ‘this’ keyword

Answer №2

In order to maintain the correct reference to 'this', you have two options for handling this situation.

Option 1:

getCurrentLocation() {
// Your Method
}, this.logging().bind(this))

logging() {
// Do something
}

Option 2:

getCurrentLocation() {
// Your Method
}, () => {// Do something})

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

Uncertainty surrounding dynamic bootstrapping in @NgModules

After successfully installing rc7, my module and component are functioning as expected. Now, I am looking to utilize it on a webpage by only bootstrapping modules and components if the current page contains the necessary selector. Although I have declare ...

The variable type does not align with the export type

My TypeScript project includes a file that loads environment variables and exports them: const.ts: const { VARIABLE0, // type of VARIABLE0 is string | undefined VARIABLE1, } = process.env; if (!VARIABLE0 || !VARIABLE1) { throw new Error('Inval ...

Updating the value in React context does not result in the value being updated

I am in the process of developing a simple routing system where users can either be authenticated or not. I have been using hooks to implement this functionality, but so far, it has not been as successful as I hoped for. authProvider.tsx import React, {Di ...

Try using ngFor within the insertAdjacentHTML method

When a user clicks, I dynamically attach an element inside a template like this: this.optionValue = []; youClickMe(){ var moreput = ''; moreput += '<select">'; moreput += '<option *ngFor="let lup of opti ...

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

How can I showcase a different component within another *ngFor loop?

I am currently working on a table in HTML that displays product information. Here is the code snippet for it: <form [formGroup]="myform" (ngSubmit)="submit()" > <tbody> <tr class="group" *ngFor="let item of products;"&g ...

A step-by-step guide to accessing Chrome performance metrics using JavaScript

By utilizing Chrome Dev Tools, I am able to perform the following actions: Begin by opening Chrome Dev Tools (simply right click on any page in Chrome and select "inspect") Navigate to the "performance" tab Click on the record button Interact with a butt ...

Issue with decorators not functioning in the latest alpha version of Sequelize v7

As I was exploring sequelize v7 (alpha), I encountered multiple errors when trying out basic examples directly from their documentation. For instance, taken straight from the official documentation import { Sequelize, DataTypes, Model, InferAttributes, Inf ...

Properties undefined

All of my functions are giving errors indicating that the props are not defined. The error specifically relates to the word "props" in the following functions: function PostButton(props) function PostButton2(props) function TotalVotes(props) ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...

Guide to showing a form following a button click in Angular 9

I am trying to create a feature on my page where when I click a button, a form will appear directly below it. Additionally, I would like the number of forms displayed to match the number of times the button is clicked. Being a newcomer to Angular 9, I am ...

Unit testing an Angular component that inherits from a base component

While running a basic testcase for one of my components, I encountered an error message. The component inherits from another class. Error: TypeError: Cannot read property 'setParent' of undefined Does anyone have any suggestions on how to resol ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Differences between `typings install` and `@types` installation

Currently, I am in the process of learning how to integrate Angular into an MVC web server. For guidance, I am referring to this tutorial: After some research and noticing a warning from npm, I learned that typings install is no longer used. Instead, it ...

I'm struggling to find the right Typescript syntax for defining a thunk function that returns a value while using React Redux Toolkit

Currently, I am utilizing TypeScript within a React Redux Toolkit project. While attempting to create an Async Thunk action function that is expected to return a boolean value, I found myself struggling with determining the correct TypeScript syntax: expor ...

No routes found for URL segment 'master-system/update-system'

I seem to be missing something crucial while attempting to set up authorization for child routes. Specifically, I am trying to restrict access based on user roles - Admin and notAdmin. I have implemented an authentication check in the login.component.ts fi ...

Angular and Bootstrap are like peanut butter and jelly -

Recently, I've been delving into Angular and attempting to integrate Bootstrap into my projects. To install Bootstrap using npm, I ran the following command: cmd npm install bootstrap --save After the installation, I imported the necessary styles in ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

The ng-bootstrap package is not fully compatible with Bootstrap 4 Alpha 6, particularly when it comes to collapsible elements such as forms

Just a heads up for everyone, the current version of ng-bootstrap is not compatible with the latest release of Bootstrap (Alpha 6). This includes collapsing elements like collapses, dropdowns, navs, etc. I haven't figured out how to make the package ...