geolocation.watchPosition unsubscribe error

Dears, I’m having problems to unsubscribe the Ionic Native Geolocation.

Here is my code:

  watch:any;

  constructor(
    private geolocation: Geolocation
  ) { }

  ionViewDidLoad() {
    this.watch = this.geolocation.watchPosition();
    this.watch.subscribe((data) => {
      console.log(data);
    }
  }

  ionViewDidLeave() {
    this.watch.unsubscribe(); // <<<<---- the error occurs here
  }

I’m getting the error ERROR TypeError: this.watch.unsubscribe is not a function, why?

1 Like

Hi, you only can unsubscribe() a subscription of an observable, not the observable itself:

  watch:any;
  subscription: any;

  constructor(
    private geolocation: Geolocation
  ) { }

  ionViewDidLoad() {
    this.watch = this.geolocation.watchPosition();
    this.subscription = this.watch.subscribe((data) => {
      console.log(data);
    }); // save the subscription
  }

  ionViewDidLeave() {
    this.subscription.unsubscribe(); // <<<<---- unsubscribe the subscription (not the observable!)
  }
5 Likes

My lack of attention! :thinking:

Thank you.

I’m still having the same problem, it doesnt work.
I’m running ionic v4.

sir not work in my case watchPosition is fire continuous after unsubscribe why?