0

I'm working with Angular 2 (Typescript) on Ionic 2 App. I have one class NewFavoriteSitePage with private property siteForm and I can use this property in class methods but when I am inside one google maps method this variable is undefined. What are the scope of variable or How do I define the variable to access from both sides?

declare var google;
......
export class NewFavoriteSitePage {
  .....
  private siteForm: FormGroup;

  loadMap(){
  //I can access to siteForm here!
  .....
      google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
        let newlatLng = marker.latLng; 
        console.log(this.siteForm); //Here this.siteForm is undefined
      });
  }
georgeawg
  • 46,994
  • 13
  • 63
  • 85
CampDev
  • 1,619
  • 3
  • 14
  • 22
  • I'm testing with `public siteForm: FormGroup` but it doesn't work. – CampDev Jul 08 '17 at 19:11
  • I'm testing with `declare var siteForm: any` below `declare var google` and doesn't work too. – CampDev Jul 08 '17 at 19:17
  • this doesn't have anything to do with typescript or what type you use. You are creating a function with it's own new `this` that has nothing to do with the class itself. Use an arrow function, bind, closing over `var that = this` or one of the countless other ways to make sure `this` in the new function is what you want it to be. – ASDFGerte Jul 08 '17 at 19:21

2 Answers2

3

the reason why google maps is not defined there, is because it is the callback of a function, which makes 'this' not equal to the page anymore, putting it in a variable will fix the issue.

  private siteForm: FormGroup;

  loadMap(){
  var siteformFromPage=this.siteForm; //this should work
        google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
        let newlatLng = marker.latLng; 
        console.log(siteformFromPage);
      });
  }

EDIT: if you want the latest value, you could also try is this way:

  private siteForm: FormGroup;

  loadMap(){
       var that=this; //cache that value of the page.

        google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
        let newlatLng = marker.latLng; 
        console.log(that.siteformFromPage);
      });
  }
0

Use an arrow function to retain context:

  google.maps.event.addListener(marker, 'dragend', (marker, siteForm) => {
    let newlatLng = marker.latLng; 
    console.log(this.siteForm);
  });
Frank Modica
  • 9,053
  • 3
  • 18
  • 34
  • Can you explain me more about this `=>` (arrow function) I'm new in Ionic 2 – CampDev Jul 08 '17 at 19:32
  • @CampDev This question has been marked as a duplicate. Check the top of the page to read more about how JavaScript handles the `this` keyword. – Frank Modica Jul 08 '17 at 19:33