1

Can someone explain what am I missing - I am assigning value to property variable in the OnInit lifecycle hook, but the value disappears when trying to access it again on click event:

import {Component} from 'angular2/core';
import {OnInit} from 'angular2/core';

@Component({
    selector: 'simple-test',
    template: `<button type="button" class="btn btn-primary" (click)="getSearchResults()">
        <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search Venues
        </button>`
})

export class SimpleTestComponent implements OnInit {
    public userLoc: string;
    constructor() { }
    getSearchResults(){
        console.log('userLoc: ' + this.userLoc);
    }

    ngOnInit() {
        this.initGeoLocation();
    }

    initGeoLocation() {
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                this.userLoc = `${position.coords.latitude},${position.coords.longitude}`;
                console.log('userLoc: ' + this.userLoc);
            });
        } 
    }
}

2 Answers 2

3

First of all, you are loosing correct context inside of getCurrentPosition callback function. Use arrow function instead:

initGeoLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            this.userLoc = `${position.coords.latitude},${position.coords.longitude}`;
            console.log('userLoc: ' + this.userLoc);
        });
    } 
}

Second potential problem. You need to be aware that geolocation API is asynchronous, so the value for userLoc might be unavailable if you click too soon. Consider disabling button until current location is resolved.

Sign up to request clarification or add additional context in comments.

Comments

1

here is working plnkr for your question:

http://plnkr.co/edit/uG4rfXySQYWHzlj6iIuj?p=preview

<button type="button" class="btn btn-primary" (click)="initGeoLocation()">
        <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search Venues
</button>

2 Comments

Thank you for the answer, even though it didnt solve the problem - it shows the need for adding unit tests as you have done, and which I will try to integrate now. I wouldn't separate template into templateUrl file as in plunker for simple file, as per Angular2 style guide : Keep the components' templates as lean as possible and inline them inside of the @Component decorator. Extract the more complex and bigger templates, longer than 15 lines of code, into a separate file and put them next to their controllers' definition.
ohh thanks for posting such a great link i.e style guide for angular2.

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.