"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function of InitMap. The error message received is: TS2339 Property 'markers' does not exist on type void

 export class StudentGraphicReportMapComponent implements OnInit  {
  locations: any[] = [];
  markers:any[] = [];
  constructor(private http: Http, private  elementRef: ElementRef , private dashboardService: DashboardService) {
  }
  initMap() { 
   // ------ CAN ACCESS markers here
 
    this.locations.forEach(function(location: Location) {
         for ( let b = 0; b < location.studentCount; b++) {
           let marker = new google.maps.Marker({
             position: location,
             label: 'A'
           });
    // ----------CANNOT ACCESS markers here
           this.markers.push(marker); //Error:Property 'markers' does not exist on type void
         }
    });
  
  }
  ngOnInit() {
    this.dashboardService.getStudentCoordinates().then(data => {
      this.locations = data.data;
      this.initMap();
    });
  }

}

In need of assistance to resolve this coding issue. Thanks in advance.

Answer №1

To access the this keyword in TypeScript, it is recommended to use arrow functions. Here is an example:

export class StudentGraphicReportMapComponent implements OnInit  {
  locations: any[] = [];
  markers:any[] = [];
  constructor(private http: Http, private  elementRef: ElementRef , private dashboardService: DashboardService) {
  }
  initMap() { 
    this.locations.forEach((location: Location) => {
         for ( let b = 0; b < location.studentCount; b++) {
           let marker = new google.maps.Marker({
             position: location,
             label: 'A'
           });
           this.markers.push(marker); //Error:Property 'markers' does not exist on type void
         }
    });

  }
  ngOnInit() {
    this.dashboardService.getStudentCoordinates().then(data => {
      this.locations = data.data;
      this.initMap();
    });
  }

}

Answer №2

Point local variable towards this specific location

initializeMap() { 
let _current = this;
...
}

utilize _current.markers within the method

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

A script error occurs exclusively on dynamic routing in a static web page generated by NUXT

Currently working on a Nuxt.js website and encountering an issue. Initially, nuxt.config.js was set up as below to enable a headless CMS. export default { target: "static", ssr: true, generate: { async routes() { const pages = awa ...

JavaScript Scrolling Functionality Not Functioning as Expected

I have implemented a scroll function on my website $('#lisr').scroll( function() { if($(this).scrollTop() + $(this).innerHeight()>= $(this)[0].scrollHeight) { //Perform some action here } } However, I am encountering an ...

JavaScript - AJAX Call Terminated after a Period on Secure Socket Layer (SSL)

Currently, my AJAX calls over an SSL connection using the Prototype JS framework run smoothly initially. However, after 10 seconds of being live on the page, they start failing with a status of 0 or 'canceled' in the Network Inspector... This is ...

Achieving vertical center alignment in React Native: Tips and techniques

Just a quick heads-up: This question pertains to a school project. I'm currently knee-deep in a full-stack project that utilizes React Native for the front-end. I've hit a bit of a snag when it comes to page layout. Here's the snippet of my ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

The specified property cannot be found in the type 'IntrinsicAttributes & ...'

I'm currently working on adding a custom prop to a custom styled-component: interface Props { image?: string; title?: string; subtitle?: string; background?: string; } export function CardWide({ image, title, subtitle, background }: Props) ...

The Jquery .remove() function will only take effect after the second click

I am currently working on implementing a notifications feature using bootstrap popover. The issue I am facing is that after a user clicks on a notification, it should be removed. However, for some reason, it requires two clicks to actually remove the notif ...

Dealing with illegal characters, such as the notorious £ symbol, in JSON data within a JQuery

I'm encountering an issue with a textarea and the handling of special symbols. Specifically, when I use $('#mytextarea').val() to retrieve text that contains '£', I end up seeing the black diamond with a question mark inside it. T ...

What is the best approach for finding the xPath of this specific element?

Take a look at this website Link I'm trying to capture the popup message on this site, but I can't seem to find the element for it in the code. Any ideas? ...

Dynamic change in the mutation observer is not causing the callback to trigger

I have created a nested structure with two <div> elements. I am monitoring changes in the width of the inner <div>, which is set to width:auto;. Despite adjusting the width of the parent <div>, the mutation observer callback doesn't ...

When attempting to make a GET request, Express/Mongoose is returning a null array

I am having trouble retrieving the list of books from my database. Even though I have successfully inserted the data into Mongoose Compass, when I try to fetch it, all I get is an empty array. //Model File import mongoose from "mongoose"; cons ...

Pressing a button within an HTML table to retrieve the corresponding value in that row

How can I click a button inside an HTML table, get the value on the same row and pass it to an input field called FullName? Thanks for your help! <td><?php echo $r['signatoryname'] ?></td> <td ...

Having issues with 'direction' in React withStyles causing errors

I am experiencing an issue with my React website where I am using the withStyles feature to apply styles to a material-ui Grid element. Specifically, when attempting to use direction: "column" in the style, I encounter the error message provided below. Th ...

Can Next.js 13 components maximize performance by utilizing server and client components simultaneously? What is the best approach to achieve this?

Introduction Currently, I am exploring server and client components in Next.js 13 and looking to incorporate them into my project. One of the key features is a container component that utilizes react-intersection-observer to track which section is visible ...

JavaScript truthy values referring to numbers

According to the rules outlined below: Falsy: false 0 (zero) '' or "" (empty string) null undefinded NaN (e.g. the result of 1/0) Truthy: Anything else I'm puzzled as to why, in the tests that follow, only the number 1 is considered "tr ...

Regex tips: Matching multiple words in regex

I am struggling with creating a simple regex. My challenge is to write a regex that ensures a string contains all 3 specific words, instead of just any one of them: /advancebrain|com_ixxocart|p\=completed/ I need the regex to match only if all thre ...

Display Mailchimp subscription form adjacent to button click on a WordPress website

Seeking assistance with integrating a MailChimp simple subscription form (requires email and submit) next to a button on my Wordpress page. The desired functionality is a straightforward button labeled "Newsletter." When clicked, a small form should conve ...

Angular Image Cropping: A How-To Guide

I have been on the lookout for an Angular plugin that allows me to crop images before uploading them to the database. Despite spending all day searching, I have not been able to find a suitable plugin that meets my requirements. What I need specifically i ...

Error encountered when attempting to open PDF documents located in the ./../../../assets/pdf/file.pdf directory. Route matching failed, resulting in inability to access the

In my Angular application, I have stored the PDF file under the assets/pdf directory. Here is the code snippet: <div class="container-fluid mt-2 mb-2"> <a target="_blank" href="./../../../assets/pdf/MSW - Transition Briefing Slides v1.1.pdf"& ...

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...