Доступ к NavParams внутри провайдера, - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь получить доступ к NavParams внутри провайдера, но я знаю, что импорт NavParams не решит проблему.

Краткая информация о моем приложении, пользователь вводит свое имя и адрес, на основе карты будет указана булавка для адреса, а когда пользователь щелкнет на булавке, появится предупреждение, сообщающее имя пин-кода.

Вот мой create-event.ts, где я нажимаю имя.

toMap() {
  this.navCtrl.push('MapPage', {eName: this.eventDetail.eventName});
}

Получите на Map.ts и нажмите на markers.ts

public eName: string;

constructor (...) {
this.eName = this.navParams.get('eName');
}

addMarker() {
let prompt = this.alertCtrl.create({
  title: 'Add Marker',
  message: "Enter Adress",
  inputs: [
    {
      name: 'Address',
      placeholder: 'Enter Address'
    },
  ],
  buttons: [
    {
      text: 'Cancel',
      handler: data => {
        console.log('Cancel clicked');
      }
    },
    {
      text: 'Save',
      handler: data => {

        this.geoCodeandAdd(data.address);
        this.retrieveAddress(data.address);
      }
    }
  ]
});
prompt.present();
}
geoCodeandAdd(address) {
this.nativeGeocoder.forwardGeocode(address)
  .then((coordinates: NativeGeocoderForwardResult[]) => {

  this.markersProvider.saveMarker(coordinates[0]);
  this.navCtrl.push('MarkerProvider', {eName: this.eName});
})
.catch((error: any) => console.log(error));
}
  loadMarkers() {
this.markersProvider.getAllMarkers().subscribe((markers: any) => {
  markers.forEach(singlemarker => {
    let markerGroup = leaflet.featureGroup();

    let marker: any = leaflet
      .marker([singlemarker.latitude, singlemarker.longitude])
      .on("click", () => {
        alert(singlemarker.message);
      });
    markerGroup.addLayer(marker);
    this.map.addLayer(markerGroup);
  });
});
}

Myмаркер провайдера .ts

import { NavController, NavParams } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { AngularFirestore } from "angularfire2/firestore";

@Injectable()
export class MarkersProvider {
  public eName: string;
  constructor(private afs: AngularFirestore, public navCtrl: NavController, public navParams: NavParams) {
    console.log("Hello MarkersProvider Provider");
    this.eName = this.navParams.get('eName');
  }

  saveMarker(coords) {
    this.afs
      .collection("markers")
      .add({
        latitude: coords.latitude,
        longitude: coords.longitude,
        message: this.eName,
      })
      .then(() => {
        alert("Added");
      });
  }

  getAllMarkers() {
    return this.afs.collection("markers").valueChanges();
  }
}

трассировка стека

Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[Content -> NavController]: 
  StaticInjectorError(Platform: core)[Content -> NavController]: 
    NullInjectorError: No provider for NavController!
Error: StaticInjectorError(AppModule)[Content -> NavController]: 
  StaticInjectorError(Platform: core)[Content -> NavController]: 
    NullInjectorError: No provider for NavController!
    at _NullInjector.get (http://localhost:8100/build/vendor.js:1377:19)
    at resolveToken (http://localhost:8100/build/vendor.js:1675:24)
    at tryResolveToken (http://localhost:8100/build/vendor.js:1617:16)
    at StaticInjector.get (http://localhost:8100/build/vendor.js:1485:20)
    at resolveToken (http://localhost:8100/build/vendor.js:1675:24)
    at tryResolveToken (http://localhost:8100/build/vendor.js:1617:16)
    at StaticInjector.get (http://localhost:8100/build/vendor.js:1485:20)
    at resolveNgModuleDep (http://localhost:8100/build/vendor.js:11270:25)
    at _createClass (http://localhost:8100/build/vendor.js:11311:68)
    at _createProviderInstance$1     (http://localhost:8100/build/vendor.js:11281:26)
at c (http://localhost:8100/build/polyfills.js:3:19752)
at Object.reject (http://localhost:8100/build/polyfills.js:3:19174)
at NavControllerBase._fireError (http://localhost:8100/build/vendor.js:52760:16)
at NavControllerBase._failed (http://localhost:8100/build/vendor.js:52753:14)
at http://localhost:8100/build/vendor.js:52800:59
at t.invoke (http://localhost:8100/build/polyfills.js:3:14976)
at Object.onInvoke (http://localhost:8100/build/vendor.js:5134:33)
at t.invoke (http://localhost:8100/build/polyfills.js:3:14916)
at r.run (http://localhost:8100/build/polyfills.js:3:10143)
at http://localhost:8100/build/polyfills.js:3:20242

Есть ли способ использовать navparams внутри провайдера.

1 Ответ

0 голосов
/ 26 сентября 2018

Вам не нужны navParams для передачи значений провайдеру.Вам просто нужно передать его соответствующему методу вашего провайдера в качестве простого аргумента функции.

В вашем Map.ts:

public eName: string;

constructor (...) {
this.eName = this.navParams.get('eName');
}

addMarker() {
let prompt = this.alertCtrl.create({
  title: 'Add Marker',
  message: "Enter Adress",
  inputs: [
    {
      name: 'Address',
      placeholder: 'Enter Address'
    },
  ],
  buttons: [
    {
      text: 'Cancel',
      handler: data => {
        console.log('Cancel clicked');
      }
    },
    {
      text: 'Save',
      handler: data => {

        this.geoCodeandAdd(data.address);
        this.retrieveAddress(data.address);
      }
    }
  ]
});
prompt.present();
}
geoCodeandAdd(address) {
this.nativeGeocoder.forwardGeocode(address)
  .then((coordinates: NativeGeocoderForwardResult[]) => {

  // here pass eName as argument:
  this.markersProvider.saveMarker(coordinates[0], this.eName); 
  // removed this: this.navCtrl.push('MarkerProvider', {eName: this.eName});
})
.catch((error: any) => console.log(error));
}
  loadMarkers() {
this.markersProvider.getAllMarkers().subscribe((markers: any) => {
  markers.forEach(singlemarker => {
    let markerGroup = leaflet.featureGroup();

    let marker: any = leaflet
      .marker([singlemarker.latitude, singlemarker.longitude])
      .on("click", () => {
        alert(singlemarker.message);
      });
    markerGroup.addLayer(marker);
    this.map.addLayer(markerGroup);
  });
});
}

Теперь в вашем провайдере измените метод, который использует eName:

// remove this: import { NavController, NavParams } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { AngularFirestore } from "angularfire2/firestore";

@Injectable()
export class MarkersProvider {
  // remove this: public eName: string;
  // modify injections as you don't need nav things in your provider:
  constructor(private afs: AngularFirestore) {
    console.log("Hello MarkersProvider Provider");
    // remove this: this.eName = this.navParams.get('eName');
  }

  // here in this method add argument:
  saveMarker(coords, eName) {
    this.afs
      .collection("markers")
      .add({
        latitude: coords.latitude,
        longitude: coords.longitude,
        message: eName,
      })
      .then(() => {
        alert("Added");
      });
  }

  getAllMarkers() {
    return this.afs.collection("markers").valueChanges();
  }
}
...