La Reyna
La Reyna

Reputation: 138

Background Geolocation : Subscribe does not exist on type Promise<any>

I am using ionic 4, and trying to get user location from GPS, specifically for every 1 hour interval. So it's an app tracking the user location every hour.

I have used Ionic 4 Background location plugin documentation from their official site, and found this code to install this plugin, which says that this plugin will run even when app exits, so I hope it's what I need.

I have used the following code to install Background-Geolocation plugin to Ionic 4 app:

ionic cordova plugin add cordova-plugin-mauron85-background-geolocation@alpha
npm install @ionic-native/background-mode

But after it when I try to test it, in my app.component.ts main file, the code fails!

this.platform.ready().then(() => { 

      this.statusBar.styleDefault();
      this.splashScreen.hide();

      //setting options for backgroun-geolocatuion
      const config: BackgroundGeolocationConfig = {
        desiredAccuracy: 10,
        stationaryRadius: 20,
        distanceFilter: 30,
        debug: true, 
        stopOnTerminate: false,  
     };



      this.backgroundGeolocation.configure(config)
      .subscribe((location: BackgroundGeolocationResponse) => {

      // ERROR comes here ==> *subscribe* does not exist on type Promise<any> ???  

        alert(location.longitude);  
      });

      this.backgroundGeolocation.start();

    });

It shows this error:

 // ERROR comes here ==> Subscribe does not exist on type Promise<any>

I am not able to get the returned data as subscribed data due to this error. I need the user location data for every 1 hour interval (even if user moves or not), but this subscribe is showing the error as I stated above.

If I change subscribe to then, then it returns data for once, that too undefined.

I need this code to run with subscribe, to get regularly tracked information of user every hour.

I have imported all the providers and constructor already above the code and in main module files.

Imports:

app/app.component.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    BackgroundGeolocation, 
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Upvotes: 2

Views: 4544

Answers (6)

Scottie
Scottie

Reputation: 11308

I ran into this problem and found that the documentation is incorrect.

You need to import from @ionic-native/background-geolocation/ngx instead of @ionic-native/background-geolocation.

This will allow subscriptions.

Upvotes: 0

Naresh Bethu
Naresh Bethu

Reputation: 9

this.backgroundGeolocation.configure(config).then((location) => { this.backgroundGeolocation.on(BackgroundGeolocationEvents.location).subscribe((location: BackgroundGeolocationResponse) => { console.log('BackgroundGeolocationResponse', location); }, (err) => { console.log(err); })

Upvotes: 0

Akhil Sahu
Akhil Sahu

Reputation: 637

The implementation has changed in Ionic 4 as you can see the docs for Ionic 4. They must have updated it to promise so we can't subscribe now. Use then with promise.

https://ionicframework.com/docs/native/background-geolocation/

For Ionic 4

Following is the code snippet resolves this issue

import { BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationResponse } from '@ionic-native/background-geolocation';

constructor(private backgroundGeolocation: BackgroundGeolocation) { }

...

const config: BackgroundGeolocationConfig = {
            desiredAccuracy: 10,
            stationaryRadius: 20,
            distanceFilter: 30,
            debug: true, //  enable this hear sounds for background-geolocation life-cycle.
            stopOnTerminate: false, // enable this to clear background location settings when the app terminates
    };

this.backgroundGeolocation.configure(config)
  .subscribe((location: BackgroundGeolocationResponse) => {

    console.log(location);

    // IMPORTANT:  You must execute the finish method here to inform the native plugin that you're finished,
    // and the background-task may be completed.  You must do this regardless if your HTTP request is successful or not.
    // IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
    this.backgroundGeolocation.finish(); // FOR IOS ONLY

  });

// start recording location
this.backgroundGeolocation.start();

// If you wish to turn OFF background-tracking, call the #stop method.
this.backgroundGeolocation.stop();

For Ionic 3 if this error occurs in the background geolocation plugin .

// ERROR comes here ==> Subscribe does not exist on type Promise<any>

Remove the latest plugin and replace it with

npm rm --save @ionic-native/background-geolocation  
npm install --save @ionic-native/[email protected] 

Upvotes: 1

paridhi pathak
paridhi pathak

Reputation: 51

Mayank's answer helped me, however, version 2.2.5 generates an unsuccessful build and leads to the below error-

AAPT: error: resource android:attr/fontVariationSettings not found.

I would recommend-

$ ionic cordova plugin add [email protected]
$ npm install --save @ionic-native/background-geolocation@3

Link: https://ionic.zendesk.com/hc/en-us/articles/360001961853-Ionic-Appflow-Android-package-build-fails-with-AAPT-error

Hope this helps someone.

Upvotes: 0

Mayank R Jain
Mayank R Jain

Reputation: 3147

This seems to be a version mismatch -- lots of versions and conflicting documentation all over. After a lot of trial error,

For ionic 3 this works for me ...

$ ionic cordova plugin add [email protected]
$ npm install --save @ionic-native/background-geolocation@3

For ionic 4 try it and it may help you.

Upvotes: 1

Shubham Chaudhary
Shubham Chaudhary

Reputation: 499

this.backgroundGeoLocation.configure(config) is only for configuration of geolocation and it is a promise indicating success or failure of configuration.

First install following:

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

Now include them in your providers

app.module.ts

import {LocationTrackerProvider} from '../providers/location.provider';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation';
import { Geolocation } from '@ionic-native/geolocation';

Create location.provider.ts (which is added in app.module.ts)

location.provider.ts

import { BackgroundGeolocation } from '@ionic-native/background-geolocation';
import { Geolocation, Geoposition } from '@ionic-native/geolocation';

constructor(private backgroundGeolocation: BackgroundGeolocation){}

initLocation(){

    let config = {
        ...
    };

    this.backgroundGeolocation.configure(config).subscribe((location) => {
      console.log('BackgroundGeolocation:  ' + location.latitude + ',' + location.longitude);

    }, (err) => {
      console.log(err);
    });

}

Upvotes: 0

Related Questions