Wenbo Zhao
Wenbo Zhao

Reputation: 1

Typescript binding

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

Upvotes: 0

Views: 82

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74596

It looks like this is in scope everywhere that you use it, so I guess the issue is that this.str is accessed before it has been assigned a value.

navigator.geolocation.getCurrentPosition is asynchronous, and fires the callback to set the position on success.

You haven't shown us when this.getInfor gets called (perhaps it's obvious to someone familiar with angular) but I suspect that it is before the callback has been fired, so this.str has not yet been assigned a value.

So the solution would be to rearrange the code so the this.str was assigned a value before you try to access it.

Upvotes: 0

basarat
basarat

Reputation: 276161

To autobind you can use arrows:

location() {

becomes:

location = () => {

More

Arrow functions https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

Upvotes: 2

Related Questions