"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

Combining portions of objects in Angular2

I want to combine two identical type observables in Angular2 and return an observable of the same type in a function. My goal is to: transform this setup: obs1.subscribe(obs => console.log(obs)) (where I receive): { count: 10, array: <some ...

How to Revalidate a Next.js Dynamic Route Manually Using an API Route?

In my application built with Next.js, I have a dynamic page that displays resources at the route /resource/[id]. When a user edits a resource, such as #5, I want to refresh the cached page at /resource/5. I've created an API route in my /pages direct ...

Encountering an issue with Next.js, Typescript, and mongoose when attempting to use `let cached = global.mongoose

I attempted to create a cached mongoose connection for my Next.js + Typescript application, but the code I used was: let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } The use of global.mongoose res ...

Organizing NodeJS modules in a way that mirrors Maven's groupId concept

I am making the switch to NodeJS after working extensively with Maven. In Maven, we are familiar with the groupId and artifactID, as well as the package name when starting a new project. However, in NodeJS, I only see a module name. The concept of groupI ...

Strategies for addressing the issue of assigning "xx" to intrinsic attributes and props in React with TypeScript

I'm facing an issue where I am unable to locate 'count' and assign {count: number; title:string} type to IntrinsicAttributes in a React and TypeScript environment. There are two components involved, ParentComponent and ChildComponent. In t ...

Adjust the width of a div within a nested iframe using jQuery without the need for an identifying ID on the iframe itself

Below is the code sample I'm working with: <iframe> <div id="inner_div"> Here's some text! </div> </iframe> I am aware that by adding an id to the iframe, I could follow the instructions provided here to access t ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

Tips for effectively eliminating errors in a redux store

Within my react-redux application, I have implemented a system to catch error responses from redux-saga. These errors are saved in the redux-store and rendered in the component. However, a major challenge arises when trying to remove these errors upon comp ...

Deciphering HTML within a Vue attribute: Tips and tricks

I'm having trouble converting some code to Vue. There seems to be a rendering difference in the alt attribute of an image, and I can't figure out how to interpret the html within the attributes. I've searched for solutions but haven't f ...

What is the best way to distinguish shared services from other services in Angular 6 and above?

There was a time when I frequently heard the term "shared services" in relation to sharing data between unrelated components in Angular. However, I started questioning whether every service is actually classified as a shared service or not. If it is cons ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

PHP Dropdown List - Default option should be set to "all" (or "Alle")

My website displays data to users based on the State they reside in, with a filter provided through a drop-down list allowing them to select any specific State or view data from all States. Currently, the default selection shows the user data from their ow ...

Tips for linking an Express JS server to an Angular 6 file?

I have been researching how to create a user login system using Express, Node.js, and Angular. However, I haven't found a clear answer on how to add new pages with Angular. Can someone guide me on the process and recommend the necessary modules to use ...

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

Trigger a JavaScript alert message upon clicking the close button

I have encountered an issue with my current code. When I click on the close (X) button, it should display an error message stored in variable s. Previously, the script was functioning correctly but now it is not showing any alerts when I click on the close ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...

Transform the array within a callback function

Seeking assistance: I am grappling with the challenge of constructing an array of results within a loop of MySQL results. The ultimate goal is to populate an array with normalized objects derived from raw data. Any guidance would be greatly appreciated! ...

In JavaScript, JSON data is parsed using a comma separator

Here is the format of my data: [{"QualID":1,"Qualification":"Van Driver"},{"QualID":3,"Qualification":"Safety Cert"},{"QualID":4,"Qualification":"Welder"}] I am look ...

The error form is not responding even after attempting to locate the issue

I have created a form and it was working fine, but now when I click on the submit or reset buttons, nothing happens. I've checked my code thoroughly line by line, but can't seem to find the issue. I even tried restoring previous versions, but no ...

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...