MrLehiste
MrLehiste

Reputation: 1036

Angular2 component property variable loses value after Init()

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);
            });
        } 
    }
}

Upvotes: 1

Views: 1630

Answers (2)

Pardeep Jain
Pardeep Jain

Reputation: 86800

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>

Upvotes: 1

dfsq
dfsq

Reputation: 193301

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.

Upvotes: 3

Related Questions