将值从地理位置传递到本地方法失败

时间:2017-11-12 20:14:03

标签: angular

我想获取用户的当前位置并将其发送到网络服务,以获取该位置的当前天气。

我在我的Component的构造函数中注入我的服务。

  constructor(private owmService: OwmService) {
  }

获取位置:

  ngOnInit() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        console.log("getCurrentPosition succesful", position); //I see the value of position, it's fine.
        this.getCurrentWeatherViaPosition(position); //this fails to pass on the value :(
      });
    }
  }

错误讯息: 错误类型错误:无法读取属性' getCurrentWeatherViaPosition'为null

我想将这个位置传递给这个方法:

 getCurrentWeatherViaPosition(position: Position): void {
    this.owmService.getCurrentWeatherViaPosition(position)
      .subscribe((currentWeather: CurrentWeather) => {
        //got response from API
      });
  }

我做错了什么?我应该如何将(async?)地理定位调用的值传递给我的本地私有方法?

1 个答案:

答案 0 :(得分:1)

如果您使用

function () {...}

this将指向geoLocation

使用箭头功能

 navigator.geolocation.getCurrentPosition((position) => {

然后this将指向此代码所在的类实例。