(ionic2 angular4)将匿名回调函数的返回值传递给'this'

时间:2017-09-20 15:11:09

标签: angular ionic2 ionic3

我正在使用我所制作的地理定位提供商,它是异步的。获取用户的位置需要大约3-5秒。我正在使用回调匿名函数,当我在console.log时,一切都按预期工作,我读取了值。

但是当我尝试使用THIS将值设置为类变量时,则说这是未定义的。这是我的代码。 locationTracker是我提供的提供商。

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SettingsPage } from '../settings/settings'
import { ListPage } from '../list/list'
import { Geolocation } from '@ionic-native/geolocation';
import {Observable} from 'rxjs/Rx';
import { LocationTrackerProvider } from '../../providers/location-tracker/location-tracker';

export class HelloIonicPage {
      public latitude:number = null;
      public longitude:number = null;

constructor(public navCtrl: NavController, public locationTracker: LocationTrackerProvider) {

    locationTracker.updateCoordinate(function (coords) {
        console.log(coords); // here it works perfectly
        this.latitude = coords.latitude; // TypeError: this is underfinded
        return coords;
    });

}

问题是如何将值传递给纬度变量,因为这不是识别出来的?

我不打算将其保留在构造函数中,但出于演示原因,我暂时将其保留在那里。

1 个答案:

答案 0 :(得分:0)

我正在回答自己,以防有人搜索同样的内容 - 就像@yurzui所说的那样,将主要功能更改为按预期工作:

locationTracker.updateCoordinate((coords) =>{
      this.latitude = coords.latitude;
      this.longitude = coords.longitude;
 });
相关问题