打字稿绑定

时间:2017-11-03 00:06:34

标签: angular typescript

我现在正在学习Typescript,我有问题,当我想做getLocation()函数时,我想将从此函数声明的str分配给在getLocation()函数中计算的纬度+经度。但它总是说str是未定义的。我不知道为什么。可以帮助我吗?谢谢!

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

2 个答案:

答案 0 :(得分:2)

要自动搜索,您可以使用箭头:

location() {

成为:

location = () => {

更多

箭头功能https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

答案 1 :(得分:0)

看起来this在您使用它的任何地方的范围内,所以我想问题是在为this.str分配值之前访问navigator.geolocation.getCurrentPosition

this.getInfor是异步的,并触发回调以设置成功的位置。

this.str被调用时,你没有向我们展示过(对于熟悉angular的人来说,这可能是显而易见的)但是我怀疑它是在回调被触发之前,所以this.str尚未被发现分配了一个值。

因此解决方案是重新安排代码,以便在您尝试访问代码之前为int array[MAX - MIN]; 分配一个值。