0

i am trying to create a function to get the location value to pass it to all the components using shared service below is my ngOnInit function

   this.input = document.getElementById('google_places_ac');
        var autocomplete = new google.maps.places.Autocomplete(this.input, { types: ['(cities)']});
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place=autocomplete.getPlace();
           this.setValue(place.address_components[3].long_name, place.address_components[2].long_name, place.address_components[1].long_name);

         });

the problem is that it doesn't recognize this.setvalue function which shares value with my shared service or any variable with this.variable , its javascript "this" issue . and i can not even get this function to work with my constructor, it throws error at getElmentById.

there are solutions with arrow functions and all but i dont know how to use it in this condition so please help me..

1 Answer 1

1

Inside the place_changed-callback the keyword this points to the Autocomplete-instance.

You'll need to create a closure:

var instance    = this, 
    autocomplete;
instance.input  = document.getElementById('google_places_ac');
autocomplete    = new google.maps.places.Autocomplete(instance.input, { 
                     types: ['(cities)']});

google.maps.event.addListener(autocomplete, 'place_changed', function () {
   var place=this.getPlace();
   instance.setValue(place.address_components[3].long_name,          
                     place.address_components[2].long_name, 
                     place.address_components[1].long_name);
});
Sign up to request clarification or add additional context in comments.

2 Comments

var instance = this; is working , i am not getting any errors but its not updating values on the view should i create a new question for this or should i update question with my sharedservice function?
hi i have created new question if you can help me tehre it wil be great stackoverflow.com/questions/36387480/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.