2016-12-02 54 views
0

如何查看我的模板中返回的座標?在Angular2視圖中訪問變量

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; 

我希望能夠使用{{緯度}}和{{經度} }在我的模板中

回答

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

如果你想更angular2/rxjs導向:

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

} 

,然後在您的視圖:

<div>lat: {{(geoData$|async)?.latitude}}</div> 
+0

謝謝。我是否需要特別在我的.ts文件的頂部導入任何東西? – Chris

+0

取決於rxjs版本。如果沒有,請嘗試它,它應該在操作員之下 – Meir