我试图在ionic2 hello world项目中使用地理定位,我按照official site上的说明添加了ionic插件"地理定位".

我运行了以下两个命令:

$ ionic plugin add cordova-plugin-geolocation
$ npm install --save @ionic-native/geolocation

这是我的家.ts:

import { Component } from '@angular/core';
import {Geolocation} from '@ionic-native/geolocation'
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  map:any=null;
  geoInfo:any={
      resp:'',
      data:''
  };

  constructor(
      public navCtrl: NavController,
      private geolocation: Geolocation
  ) {

  }

  test(){
      this.geolocation.getCurrentPosition().then((resp) => {
          this.geoInfo.resp=JSON.stringify(resp);
          // resp.coords.latitude
          // resp.coords.longitude
      }).catch((error) => {
          console.log('Error getting location', error);
          this.geoInfo.resp='Error getting location';
      });

      let watch = this.geolocation.watchPosition();
      watch.subscribe((data) => {
          this.geoInfo.data=JSON.stringify(data);
          // data can be a set of coordinates, or an error (if an error occurred).
          // data.coords.latitude
          // data.coords.longitude
      });

  }

}

然而,我在chrome的控制台中出现了以下错误:

EXCEPTION: Error in ./TabsPage class TabsPage - inline template:0:0 caused by: No provider for Geolocation!
error_handler.js:56ORIGINAL EXCEPTION: No provider for Geolocation!

screenshot

起初我以为这是因为我在浏览器中调试,但后来我在我的Android手机中遇到了同样的错误.

那么,"没有地理定位Provider "是什么意思?我应该如何在ionic2项目中使用地理定位?

谢谢!

推荐答案

您需要将提供者添加到NgModule,即模块.在提供者之下,

providers: [
  Geolocation
]

Typescript相关问答推荐

如何获取嵌套对象属性的正确类型?

Typescript:假设foo不在类型栏中,而它在:如何调试

如何使用TypScript和react-hook-form在Next.js 14中创建通用表单组件?

如何获取数组所有可能的索引作为数字联合类型?

相同端点具有不同响应时的RTKQuery类型定义

带有微前端的动态React路由问题

APP_INITIALIZER—TypeError:appInits不是函数

防止获取发出不需要的请求

当使用`type B = A`时,B的类型显示为A.为什么当`type B = A时显示为`any `|用A代替?

在键和值为ARGS的泛型函数中未正确推断类型

如何通过TypeScript中的工厂函数将区分的联合映射到具体的类型(如类)?

如何将泛型对象作为返回类型添加到类型脚本中

从TypeScrip中的其他类型检索泛型类型

Typescript 中相同类型的不同结果

有没有一种更好的方法来存储内存中的数据,而不是在类型脚本中使用数组和基于索引的函数?

打字:注解`是字符串`而不是`布尔`?

类型分布在第一个泛型上,但不分布在第二个泛型上

定义一个只允许来自另一个类型的特定字符串文字的类型的最佳方式

递归JSON类型脚本不接受 node 值中的变量

剧作家测试未加载本地网址