Issue with Angular2: not maintaining connection with observable

I am working on an Ionic/Angular2 app where I have integrated a Google Map into the view. Within my code, I have an observable named markers, which is essentially an array of Google Maps marker objects. These markers are pushed to the array to display them on the map, and event listeners are added to each marker. While the clicking functionality works fine, I notice that I lose access to this.markers. I am wondering why this is happening and how I can create a plain variable that remains accessible throughout the class.

Below is a snippet of my code:

 export class MapView
 { 
   markers: any;

   ngOnInit()
   {
     // Initialization for the map and raw marker array data not shown here
     this.addListeners()
   }

   addListeners() // Function works properly (this.markers is accessible)
   {
     console.log(this.markers) // Displays the markers array correctly
     for(var i = 0; i < this.markers.length; i++)
     {
       this.markers[i].addListener("click",this.markerClicked, this);
     }
   }

   markerClicked(marker) // The clicked marker is passed as a parameter
   {
     console.log(this.markers);
     // Here lies the issue. The console indicates that the markers array is empty when called from this function
   }
 }

Answer №1

It appears that the issue arises when your callback function this.markerClicked is executed, causing it to lose its connection to the class and making this.markers inaccessible.

I can suggest two possible solutions:

1) One option is to refactor your callback function and define it using an arrow function, as arrow functions maintain the context of this.

this.markers[i].addListener("click", (marker) => {
  // perform actions involving marker and this.markers
  console.log(this.markers);
}, this);

2) Another approach, albeit slightly unconventional, is to try binding your callback function back to the class.

You could attempt something like this.markerClicked.bind(this) instead of simply using this.markerClicked.

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

Customize the text color of select list options in Angular 5

Is there a way to style the foreground colors of select list options differently in this dropdown code? <select id="tier" class="form-control" [(ngModel)]="tierId"> <option *ngFor="let m of tierList" value="{{m.tier}}" > {{m.option ...

Is it possible to subscribe to changes in an input type file using FormControl?

After subscribing to the FormControl.valueChanges() triggered by selecting a file on an input, I noticed that the value emitted does not include the full file path. Is there a way to access this information through subscription, or do we need to retrieve i ...

How can we simultaneously execute multiple HTTP requests in Angular 6 by leveraging the power of forkJoin and ngrx?

Current Situation In the realm of my angular6 application, I find myself juggling three distinct categories: catA, catB, and catC. Each of these categories requires data retrieval from 3 separate APIs. Upon selecting any category, the CategoryDetailsCompo ...

"Troubleshooting asynchronous requests in Angular and the issue with Http.get method

I have encountered an issue with my code while trying to make a http request to obtain the client's geoLocation and sending it to my API using http.get as a parameter. Although I have successfully implemented both functionalities, I am facing challeng ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

The Material Angular components fail to load

Just started a brand new project using Angular and Material design UPDATE : Check out the live editor on StackBlitz: here Working on implementing the toolbar example, but here's what I have so far: https://i.sstatic.net/MUVWb.png Tried inserting t ...

Do Angular routes need to have distinct prefixes?

I have defined two routes. /apples---> AppleComponent, /apples/:id ---> AppleDetailComponent, When I visit /apples/111, it will first go into AppleComponent and then into AppleDetailComponent. What steps should I take to make it only match /appl ...

One way to organize data from my API is by sorting it based on two date conditions. If one of those conditions is missing, the data should be placed at the beginning of the list

I am facing a challenge with sorting the return from my API based on the StartDate. However, I need to implement a validation where if there is no FinalDate provided, the data should appear at the first index of the result. StartDate: "2004-06-04" ...

Is there a surefire method to ensure that ChromeDriver in Protractor consistently uses the stable version?

Every time Chrome releases an update, I encounter a recurring issue. Allow me to paint the picture: All browsers are at version 83 of Chrome Chrome announces that version 84 is on its way, but it has not been released yet. A new ChromeDriver 84 is rolled ...

Detecting hidden child divs due to overflow: hidden in Angular6

Below is the particular issue I am aiming to address. <div class="row" style="overflow:hidden;"> <app-car *ngFor="let car of cars; trackBy: trackByFunction" [car]="car" > </app-car> </div> <button> ...

core.js encountered an ERROR at line 9110: TypeError - Unable to access the 'post' property as it is undefined

Currently, I am in the process of developing an API to integrate LinkedIn login functionality into an Angular application. To achieve this, I have been following the step-by-step documentation provided by LinkedIn, which can be found at the following link: ...

Ionic's concealment feature fails to function properly for animations

I recently started learning about the Ionic framework and I'm attempting to incorporate a fade animation on a 'card' element using CSS. However, despite setting a 1-second transition duration, the targeted element simply disappears after a b ...

Is Ionic 3 Experiencing a FatalException.Exception Error Due to a Bug in the Latest Release?

Recently, I downloaded Ionic 3 and everything was running smoothly until yesterday when an unexpected error started appearing after every command I tried to execute (such as ionic info, ionic serve, ionic start, etc.): { Error at FatalException.Ex ...

"Enhance Your Form with Radio Buttons Offering an Alternative Selection

Currently, I am developing a reactive form in Angular. The initial inquiry on the form prompts users to indicate their favorite fruit. I am considering including an additional "other" option. <p> <label for="favFruit"><b>Wha ...

Navigating the angular interface for Google Maps - tips for accessing the map directly

I'm currently working with Angular 14 and utilizing the Google Maps component from https://github.com/angular/components/tree/main/src/google-maps While I have successfully loaded a map on my screen, I am now trying to incorporate the Places API. Unf ...

What is causing the large build size when using Webpack with Vue.js?

After cloning the repository at: https://github.com/Microsoft/TypeScript-Vue-Starter I executed npm scripts: npm install npm run build The outcome: the size of build.js file is approximately 1MB. Can anyone explain why the build.js file is significant ...

Why is the angular navigation bar not appearing on the screen?

Currently, I am in the process of learning Angular through a Udemy course instructed by Maximilian Schwarzmuller. One of the topics he covers is creating a navigation bar. I have tried to implement the same code for my navigation bar, but unfortunately, it ...

The specified JSX element does no possess any constructors or callable signatures

The root element on the right side of my page is a simple React element that I am currently using. Can you help me troubleshoot and fix the error that is being displayed? https://i.sstatic.net/xdDyn.png ...

Implementing the ternary operator on a nested object field in typescript to enforce type validation

Is there an issue with my code or is this intentional? I want to write something similar to this. type MyDefinition = { salutation: string; value?: { typeOfValue: string; val?: string }; }; function create(name: string, input?: Partial<MyDefin ...

What is the process for combining two interface declarations into a single interface?

I have a question regarding organizing the properties of an interface: export interface IInvoicesData { invoice: IInvoice; invoiceWithTotals: IInvoice & IInvoiceTotals; } Currently, everything is functioning smoothly and I am able to consolid ...