2
votes

Géolocalisation en arrière-plan: l'abonnement n'existe pas sur le type Promise

J'utilise ionic 4 et j'essaie d'obtenir la position de l'utilisateur à partir du GPS, en particulier toutes les heures. C'est donc une application qui suit l'emplacement de l'utilisateur toutes les heures.

J'ai utilisé la documentation du plugin Ionic 4 Background location sur leur site officiel, et j'ai trouvé ce code pour installer ce plugin, qui dit que ce plugin fonctionnera même lorsque l'application se termine, donc J'espère que c'est ce dont j'ai besoin.

J'ai utilisé le code suivant pour installer le plugin Background-Geolocation sur l'application Ionic 4:

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 {}

Mais après, quand j'essaye de le tester, dans mon fichier principal app.component.ts, le code échoue!

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

Il montre cette erreur:

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();

    });

Je suis impossible d'obtenir les données renvoyées en tant que données souscrites en raison de cette erreur. J'ai besoin des données de localisation de l'utilisateur pour chaque intervalle d'une heure (même si l'utilisateur déménage ou non), mais cet abonnement affiche l'erreur comme indiqué ci-dessus.

Si je change de s'abonner à puis , puis il renvoie des données pour une fois, trop indéfinies.

J'ai besoin de ce code pour s'exécuter avec subscribe, pour obtenir régulièrement des informations de suivi de l'utilisateur toutes les heures. p >

J'ai importé tous les fournisseurs et constructeur déjà au-dessus du code et dans les fichiers du module principal.

Importations:

app / app.component.ts em>

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


3 commentaires

Pouvez-vous afficher les importations et le constructeur de ce fichier?


oui j'ai édité ma requête maintenant.


Si j'utilise "then" à la place de "subscribe, j'obtiens location.longitude" comme indéfini et juste une fois.


6 Réponses :


0
votes

this.backgroundGeoLocation.configure (config) est uniquement pour la configuration de la géolocalisation et c'est une promesse indiquant le succès ou l'échec de la configuration.

Première installation suivant:

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);
    });

}

Incluez-les maintenant dans vos fournisseurs

app.module.ts

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

Créez location.provider.ts (qui est ajouté dans app.module.ts )

location.provider.ts

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


2 commentaires

Ne marche pas. J'ai utilisé votre code this.bgl.on () et l'ai démarré mais j'ai eu une erreur attendue 1 paramètre obtenu 2, avec cet appel on (). Je suppose que j'ai dû remplacer mon ancien this.bgl.configure () {} par le code que vous avez fourni?


Vérifiez cet exemple, cela semble fonctionner github.com/himeshsuthar/ionic3-background-geo -location Vous devez installer quelques paquets supplémentaires et les inclure dans vos fournisseurs



1
votes

Cela semble être une incompatibilité de version - beaucoup de versions et de documentation contradictoire partout. Après de nombreuses erreurs d'essai,

Pour l'ionic 3 cela fonctionne pour moi ...

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

Pour ionic 4 essayez-le et cela peut vous aider.


0 commentaires

0
votes

La réponse de Mayank m'a aidé, cependant, la version 2.2.5 génère une compilation infructueuse et conduit à l'erreur ci-dessous-

AAPT: erreur: ressource android: attr / fontVariationSettings not found.

Je recommanderais-

$ plugin cordova ionique ajouter cordova-plugin-mauron85-background-geolocation@2.3.5
$ npm install --save @ ionic-native / background-geolocation @ 3

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

J'espère que cela aide quelqu'un.


2 commentaires

J'ai tout essayé, mais les services d'arrière-plan cessent de fonctionner après 5 à 10 minutes, ils reprennent après que vous ayez essayé de mettre l'application au premier plan.


Pouvez-vous confirmer que vous testez sur quelle version d'Android? Je ne suis pas confronté à ce problème



1
votes

L'implémentation a changé dans Ionic 4 comme vous pouvez voir la documentation pour Ionic 4. Ils doivent l'avoir mis à jour pour que nous puissions nous abonner maintenant. Utilisez alors avec promesse.

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

Pour Ionic 4

L'extrait de code suivant résout ce problème

npm rm --save @ionic-native/background-geolocation  
npm install --save @ionic-native/background-geolocation@5.0.0-beta.21 

Pour Ionic 3 si cette erreur se produit dans le plugin de géolocalisation en arrière-plan.

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

Supprimez le dernier plugin et remplacez-le par

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();


0 commentaires

0
votes

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


0 commentaires

0
votes

J'ai rencontré ce problème et j'ai trouvé que la documentation est incorrecte.

Vous devez importer depuis @ ionic-native / background-geolocation / ngx au lieu de @ ionic-native / background-geolocation .

Cela permettra les abonnements.


0 commentaires