无法读取null typeScript的属性'str'

时间:2017-11-02 18:37:31

标签: typescript

我正在学习TypeScript,当我想获取我的位置然后使用Googlemap API获取有关街道和城市的信息时,我无法解决这个问题。它总是说无法读取属性'str'的null 在...我不知道为什么。有人可以帮助我吗?

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) {
    this.dataSource = this.http.get('https://maps.googleapis.com/maps/api/geocode/json?'
      + 'latlng=' + this.str + '&key=AIzaSyC2wdo6kMAXpuhwuUa8fM4mCkDy_kZeWKY').map(Response => Response.json());
  }
  ngOnInit() {
  }
  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(this.showPostion, this.showError);
    }
  }
  showPostion(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    this.str.bind(this);
    this.str = String(latitude + ',' + longitude);
    console.log(this.str);
  }
  showError() {
    console.log('Invalid Address !');
  }
  getData() {
    this.dataSource.subscribe(
      data => this.locationInfo = data
    );
    console.log(this.locationInfo);
  }
}

1 个答案:

答案 0 :(得分:0)

您必须将回调绑定到当前类(TS不会为您执行此操作) 试试navigator.geolocation.getCurrentPosition(this.showPostion.bind(this), this.showError.bind(this)); Als删除this.str.bind(this);(绑定仅用于函数)