如何在多个离子 4 页面中使用地理定位服务?

How do use geolocation service in multiple ionic 4 pages?

我已经构建了一个地理定位服务,我希望在 home.page

上使用 getUserPosition() 方法

location.service.ts

import { Injectable } from '@angular/core';
import { Geolocation, GeolocationOptions, Geoposition, PositionError } from '@ionic-native/geolocation/ngx';

@Injectable({
  providedIn: 'root'
})
export class LocationService {
  options: GeolocationOptions;
  currentPos: Geoposition;
  loc: any;

  constructor( private geolocation: Geolocation ) { }

  getUserPosition() {
    return new Promise((resolve, reject) => {
    this.options = {
      maximumAge: 3000,
      enableHighAccuracy: true
    };

    this.geolocation.getCurrentPosition(this.options).then((pos: Geoposition) => {
    this.currentPos = pos;
    const location = {
      lat: pos.coords.latitude,
      lng: pos.coords.longitude,
      time: new Date(),
    };
    console.log('loc', location);
    resolve(pos);
  }, (err: PositionError) => {
    console.log("error : " + err.message);
    reject(err.message);
    });
  });
  }
}

我在 home.page

中访问该服务

home.ts

import { Component, OnInit } from '@angular/core';
import { LocationService } from '../../services/geolocation/location.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class WorkalonePage implements OnInit {

  getPosition: any;

  constructor( 
    private LocationService: LocationService
    ) {}

  ngOnInit() {
    this.getPosition = this.LocationService.getUserPosition;
  }
}

home.html

<ion-content>
  <ion-button expand="full" color="primary" (click)="getUserPosition()">Get Location Sevice</ion-button>
</ion-content>

但是当我在我的 html 上单击 (click)="getUserPosition()" 时,我收到错误 getUserPosition() is not a function。我一直在网上寻找答案,但所有答案都涉及使用 home.ts 文件中的地理定位。任何帮助将不胜感激。

根据我在 home.ts 中看到的情况,您尚未定义名为 getUserPosition 的函数。

按照下面的内容添加一些内容到 home.ts:

getUserPosition() {

  this.LocationService.getUserPosition().then((pos) => {

    this.getPosition = pos;

  });

}

You can directly call your service method in html like this

LocationService.ts

getUserPosition() {

  this.LocationService.getUserPosition().then((pos) => {

    this.getPosition = pos;

  });

}

在home.ts

中定义服务对象
constructor(public ls:LocationService){}

在home.html

<ion-button expand="full" color="primary" (click)="ls.getUserPosition()">
Get Location Sevice
</ion-button>