I'm learning Typescript now and i have problem that when i want to do getLocation() function, i want to assign str which declared out of this function to latitude + longitude which is compute in getLocation() function.But it always said that str is undefined.I do not know why.Can some one help me? Thanks!
import { Component, OnInit } from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/';
@Component({
selector: 'app-center',
templateUrl: './center.component.html',
styleUrls: ['./center.component.css']
})
export class CenterComponent implements OnInit {
dataSource: Observable<any>;
locationInfo: any;
str: any;
constructor(public http: Http) {
}
ngOnInit() {
}
location() {
this.getLocation();
//console.log(this.str);
//this.getInfor();
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPostion.bind(this), this.showError.bind(this));
}
}
showPostion(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
this.str = String(latitude + ',' + longitude);
console.log(this.str);
}
showError() {
console.log('Invalid Address !');
}
getInfor() {
this.dataSource = this.http.get('https://maps.googleapis.com/maps/api/geocode/json?'
+ 'latlng=' + this.str + '&key=<mykey>').map(Response => Response.json());
this.dataSource.subscribe(
data => this.locationInfo = data
);
}
}
this.strgets set. I see that it gets set inshowPostion, which gets called bygetLocation, which gets called bylocation, which gets called where?positionvariable to see what it contains whenshowPositionis called? Of coursestris empty in thelocation()method, sincegetLocationdid not return anything yet. You could init your component withstr : string = "finding position"to make sure it's never undefined.