【问题标题】:ionic 2 Geolocation clearWatch or unsubscribeionic 2 Geolocation clear观看或退订
【发布时间】:2017-08-15 14:38:34
【问题描述】:

所以我正在使用 Google Maps 和 Ionic 2。Cordova 有一个用于检索用户地理位置的插件,我有两个关于该插件的问题。

但在我提出问题之前,这是我的代码

import { Geolocation } from 'ionic-native';

watchPosition(marker) {
    let watch = Geolocation.watchPosition({
        //enableHighAccuracy: true
    });

    watch.subscribe((pos) => {
        marker.setPosition({
            lat: pos.coords.latitude,
            lng: pos.coords.longitude
        });
    });

    // stop watching if the user starts dragging the map
    this.map.addListener('dragstart', () => {
        // There might be two ways to do this, but non of them works
        watch.unsubscribe();
        Geolocation.clearWatch(watch);
    });
}
  1. AFAIK,有两种方法可以停止查看用户的位置:watch.unsubscribe()Geolocation.clearWatch(watch)。但是,我不知道除了unsubscribe 的类型是Observable 而另一个是从Geolocation 插件导入的有什么区别。我应该使用哪一个?

  2. 上面的问题实际上是微不足道的,我现在最重要的问题是它们都不起作用。 watch.unsubscribe() 给出[ts] Property 'unsubscribe' does not exist on type 'Observable<Geoposition>'.Geolocation.clearWatch(watch) 给我的错误[ts] Property 'clearWatch' does not exist on type 'typeof Geolocation'. 我有什么遗漏吗?

【问题讨论】:

    标签: cordova ionic-framework geolocation ionic2 cordova-plugins


    【解决方案1】:

    虽然有点晚了……

    • watchPosition() 返回一个 Observable
    • 你可以订阅这个 Observable
    • subscribe() 调用返回一个订阅
    • 从订阅中,您可以取消订阅()

    把它们放在一起:

    let subscription = this.geolocation.watchPosition().subscribe(
        (position) => { ... },
    );
    
    ...
    
    subscription.unsubscribe();
    

    【讨论】:

      【解决方案2】:

      如果您查看Ionic Native Typescript wrapper 中的geolocation plugin,您可以看到:

      • 它不会直接暴露clearWatch() 函数
      • its watchPosition() wrapper 返回一个 Observable,其 unsubscribe() 操作是使用内部 watchId 在地理定位插件上调用 clearWatch()。因此,清除手表的 Ionic Native 方法是在 Geolocation.watchPosition() 返回的 Observable 上调用 unsubscribe()

      但是,如果由于某种原因不起作用,您可以直接调用插件 API:

      declare var navigator: any;
      
      // Add watch
      let watchId = navigator.geolocation.watchPosition((position) => {
          // do something with position
      } , (error) => {
          // do something with error
      }), options);
      
      // Clear watch
      navigator.geolocation.clearWatch(watchId);
      

      【讨论】:

      • 谢谢!这回答了我的问题。顺便说一句,我想你的意思是clearWatch(watchId) 在最后一行。
      • ionic 的地理位置 watchPosition 返回的 observable 没有 unsubcsribe 方法时怎么办?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多