在Angular2视图中访问变量

时间:2016-12-02 15:24:44

标签: angular

如何查看模板中返回的坐标?

export class DashboardPage {
  constructor(public navCtrl: NavController) {
    Geolocation.getCurrentPosition().then(pos => {
        console.log(pos.coords.latitude, pos.coords.longitude);
    });
  }
}

我试过了:

export class DashboardPage {

  constructor(public navCtrl: NavController) {

    Geolocation.getCurrentPosition().then(pos => {
        this.latitude = pos.coords.latitude;
        this.longitude = pos.coords.longitude;
    });

  }

}

但这给了我一个错误:

Typescript Error
Property 'latitude' does not exist on type 'DashboardPage'.
src/pages/dashboard/dashboard.ts
Geolocation.getCurrentPosition().then(pos => {
this.latitude = pos.coords.latitude;
this.longitude = pos.coords.longitude;

我希望能够在我的模板中使用{{latitude}}和{{longitude}}

2 个答案:

答案 0 :(得分:2)

您需要声明您的属性:

export class DashboardPage {

  latitude: number;
  longitude: number;

  constructor(public navCtrl: NavController) {

    Geolocation.getCurrentPosition().then(pos => {
        this.latitude = pos.coords.latitude;
        this.longitude = pos.coords.longitude;
    });
  }
}

答案 1 :(得分:1)

如果你想更加面向angular2 / rxjs:

export class DashboardPage {
  geoData$: Observable<any>;
  constructor(public navCtrl: NavController) {
    this.geoData$ = Observable.fromPromise(Geolocation.getCurrentPosition());
  }

}

然后在你看来:

<div>lat: {{(geoData$|async)?.latitude}}</div>
相关问题