Using NavParams within a service component,

I'm facing a challenge in accessing NavParams within a provider, and simply importing NavParams is not solving the issue.

Here's a brief overview of my application: users input their name and address, a pin is dropped on the map based on the address provided. When the user clicks on the pin, an alert displaying the name associated with the pin pops up.

This is the section from my create-event.ts where I push the event name:

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

The data is then retrieved in Map.ts and pushed to markers.ts:

public eName: string;

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

addMarker() {
// Function code here
}

geoCodeandAdd(address) {
// Function code here
}

loadMarkers() {
// Function code here
}

Next, let's take a look at the marker provider .ts file:

// Marker Provider code here

Following that, there is a stack trace error detailing issues related to NavController:

Error message here

In conclusion, I am exploring ways to effectively utilize navparams within the provider for smoother functionality.

Answer №1

There is no need for navParams when passing values to the provider. Simply pass it as an argument to the relevant method in your provider.

In your 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[]) => {

  // pass eName as an argument here:
  this.markersProvider.saveMarker(coordinates[0], 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);
  });
});
}

Now in your provider, update the method that uses eName:

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

@Injectable()
export class MarkersProvider {
  
  constructor(private afs: AngularFirestore) {
    console.log("Hello MarkersProvider Provider");
  }

  // add argument to this method:
  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();
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate module within Typescript

Hello everyone, I am facing a problem similar to this one: I have an app written in TypeScript, and within it, I have imported import { Component } from '@angular/core'; import {CORE_DIRECTIVES} from '@angular/common'; import { MODA ...

Arrange elements within an array according to a specific property and the desired sorting sequence

Looking for a way to sort an object array in Angular 16+ based on status. The desired status order is: [N-Op, Used, Unknown, Op] Here's the sample data: const stockList = [ { 'heading': 'SK', 'status': &a ...

What is causing the undefined value for the http used in this function?

My Code Component import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-root', template: '<button id="testBtn"></button>' }) export c ...

Generate a versatile Union type featuring a mapped property

I am currently working with different types of data enum DataTypes { Email = 'email', Checkbox = 'checkbox', } type DataTypeValues = { [DataTypes.Email]: string; [DataTypes.Checkbox]: boolean; }; type Type1<T extends DataTy ...

Comparing angular2/core and @angular/core: What sets them apart?

Maybe this is a silly question, but I've noticed that there are multiple instances of import {Component} from 'angular2/core' and import {Component} from '@angular/core' However, I can't seem to grasp when to use one ove ...

Angularv9 - mat-error: Issue with rendering interpolated string value

I have been working on implementing date validation for matDatepicker and have run into an issue where the error messages do not show up when the start date is set to be greater than the end date. The error messages are supposed to be displayed using inter ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. https://i.sstatic.net/0dfxd.png Click here for image description However, we are looking to transition this functionality ...

Different varieties of TypeScript's keyof when working with objects

I am grappling with the concept of TypeScript's types when incorporating the keyof type operator on objects. Check out this example: type TypeA = { [k: number]: boolean }; type AKey = keyof TypeA; // ^? type AKey = number type TypeB = { [k: string] ...

The p-calendar feature is experiencing compatibility issues with Internet Explorer, Edge, and Firefox

While I've had success using primeng p-calendar on Google Chrome, I've encountered an issue where the date-picker does not open upon clicking the text box on other browsers. Below is the snippet of HTML code I utilized: <p-calendar [(ngModel ...

Clear all events from an HTML element and its descendants with TypeScript

Each time the page loads, I have HTML from an API that is constantly changing. Is there a way to strip away all events attached to it? The original HTML looks like this: <div id="content"> <h2 onclick="alert('hi');">Test 1< ...

Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to c ...

Guide on dividing a URL string in Angular framework

Is there a way to include a value directly in the URL, like so: http://example.com/component/july2021 I need to extract july2021 from the component and separate it into "july" and "2021". How can I achieve this? ...

Firebase push notification not working in device to device communication

I am developing an Android app and I want authenticated users to be able to send push notifications to each other through a message box. My app is built using node.js with Firebase cloud functions, but I encountered an issue while reviewing the logs: Ty ...

Simulating chained responses in Express using JEST

I am relatively new to using jest and typescript, currently working on creating a unit test for a controller function in jest import { Request, Response } from 'express'; const healthCheck = (_req: Request, _res: Response) => { const value ...

The Battle of Identifiers: Named Functions against Anonymous Functions in TypeScript

When it comes to performance and performance alone, which option is superior? 1) function GameLoop() { // Performing complex calculations requestAnimationFrame(GameLoop); } requestAnimationFrame(GameLoop); 2) function GameLoop() { // ...

After the click event, the variable in the Angular .ts file does not get refreshed

Great! I have a service in my .ts component that loops through an array of court names. Every time I click on a next or back arrow event, a counter is incremented starting at 0, where index 0 corresponds to field 1 and so on. The issue I'm facing is ...

The power of negative multiplication in TypeScript and React

I am working with a state variable called sortDirection const [sortDirection, setSortDirection] = useState<1 | -1>(1); My goal is to allow a button to toggle the state variable like this setSortDirection(sortDirection * -1); However, I encounter a ...

Glistening - mythical figure with moving brochure

In my project, I am working on an animated map that displays points color-coded by different groups provided by user input. However, not all groups appear at every time stamp in the animation. I want the legend to show all groups selected by the user, even ...

What is the method for determining the data type of a column in an Excel sheet that has been

Currently, I am utilizing the XLSX npm library to convert an Excel sheet into JSON format. However, all of the retrieved data is currently being returned as strings. To see a demo of the XLSX read process, you can visit this Stackblitz demo Is there a w ...

Include data types when destructuring arrays within a loop

Is it possible to use type annotations in for...of loops in TypeScript? For example, like this for array destructuring: for(let [id, value]: [string, number] of Object.entries(some_object)) { } Or perhaps like this for object destructuring: for(let {a, b} ...