The function service.foo is not recognized in Angular

My service function is not being recognized by my component

import { Injectable } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class LocationService {

  private coordinates: any;
  constructor(
    private toastCtrl: ToastController
  ) { }

  set setCoords(coords: any) {
    this.coordinates = coords;
    this.toastCtrl.create({
      message: `Coordinates Assigned ${this.coordinates.latitude},${this.coordinates.longitude}`
    }).then(alertCtrl => {
      alertCtrl.present();
    });
  }
  
  get getCoords(): any {
    return this.coordinates;
  }
}

This is the component (app.component.ts) where I am attempting to utilize the function:

  Geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 5000 }).then(loc => {
        alert('Latitude: ' + loc.coords.latitude + 'Longitude: ' + loc.coords.longitude);
        console.log('Location: ', loc);
        this.locationService.setCoords(loc);
      }).catch(err => {
        alert(err);
        console.log('Error while getting location:', err);
      });

Despite everything seemingly in order, I encounter the following error which puzzles me as to why the function is not being detected. Even after restarting the app and trying again, the issue persists.

Error while getting location: TypeError: this.locationService.setCoords is not a function
    at app.component.ts:56
    at ZoneDelegate.invoke (zone-evergreen.js:359)
    at Object.onInvoke (core.js:34201)
    at ZoneDelegate.invoke (zone-evergreen.js:358)
    at Zone.run (zone-evergreen.js:124)
    at zone-evergreen.js:855
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:34182)
    at ZoneDelegate.invokeTask (zone-evergreen.js:390)
    at Zone.runTask (zone-evergreen.js:168)

Answer №1

The issue is quite obvious, the usage of getters and setters can be seen here:

export class LocationService {

  private coordinates: any;
  constructor(
    private toastCtrl: ToastController
  ) { }

  set setCoords(coords: any) {
    this.coordinates = coords;
    this.toastCtrl.create({
      message: `Coordinates Assigned ${this.coordinates.latitude},${this.coordinates.longitude}`
    }).then(alertCtrl => {
      alertCtrl.present();
    });
  }
  get getCoords(): any {
    return this.coordinates;
  }
}

If you want it to be a function, consider declaring it without using the get and set keywords in front of the functions

Answer №2

My mistake, I realized that it's simply an accessor and I was attempting to access it incorrectly, the correct method is to access it without using brackets.

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

hasOwnProperty function yields no results

I need help displaying a table from JSON data. Can someone assist me with the code below? <th> { x.amountForQuantity.filter((remaining) => { return remaining.hasOwnProperty(cost.key); })[cost.key] } </th> ...

"Bringing together ECMA harmony: a nod to callbacks and generators

Initially, we are exploring uncharted territory here. Although it functions in the latest versions of Firefox, the documentation on MDN is not yet ready at the time of writing. I will address the MDN later on (maybe, as there are numerous areas needing att ...

Issues with JQuery `.click()` event

Check out this snippet of code I'm working with: $(".item").click(function () { alert("clicked!"); }); I also have (hypothetically; in reality it's more complex) the following HTML on my page: <a href="#" class="item"> ...

Toggle the enableCheckboxSelector based on a specific condition

In my implementation of angular slickgrid, the enableCheckboxSelector is set to true by default in the grid options. However, I need to selectively hide checkboxes for all rows based on a dropdown value change. I tried the following code snippet: if(isRead ...

Puppeteer experiencing issues with missing relative modules and dependencies not being found

After installing puppeteer via npm, I encountered errors when trying to compile it: This dependency was not found: * ws in ./node_modules/puppeteer/lib/WebSocketTransport.js To resolve this, you can run: npm install --save ws These relative modules we ...

What is the reasoning behind ethers.js choosing to have the return value of a function be an array that contains the value, rather than just the value itself

An issue arose with the test case below: it('should access MAX_COUNT', async () => { const maxCount = await myContract.functions.MAX_COUNT(); expect(maxCount).to.equal(64); }); The test failed with this error message: ...

Sending data from a partial view to a controller

Imagine I have two models: DailyTasks and Task. The initial view is strongly typed with the DailyTasks model, displaying a list of existing tasks for the day. Users can add more tasks to the list/table by clicking the add button. Upon clicking the add butt ...

Issue: [next-auth]: `useSession` function should be enclosed within a <SessionProvider /> tag in order to work properly

Encountering an error loading my ProfilePage where the page loads fine in the browser but an error appears in the terminal. Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider /> All child components are properly wrapped using Se ...

What is the best way to extract value from a JSON object with jQuery?

How can I retrieve the value of 'FRI' from the JSON feed returned by an AJAX call using jQuery? $.ajax({ url: query, type: "GET", dataType: "json" success: function(data) { var day = // extract data value from JSON ...

Can you explain Node.js and its applications as well as how it is commonly used?

A while back, during my time at IBM when I was immersed in learning, I came across something known as BlueMix, a cloud product. Within BlueMix, there was a rather primitive component called Node.js. Since that moment, I've been filled with curiosity a ...

Tips for utilizing the "this" keyword in JavaScript

Here's a snippet of code that I'm having trouble with: this.json.each(function(obj, index) { var li = new Element('li'); var a = new Element('a', { 'href': '#', 'rel': obj ...

Instructions for removing a single key value pair from every object in an array and transferring it to a designated object within the same array

I need to update an array of objects by adding a key and value (e.g., age:15) to an object with the name email, while removing the age property from other objects in the array. [ { name: 'test', lname: 'last', age: 5 }, ...

What sets Angular 2 apart when it comes to utilizing [ngStyle] versus [style.attribute]?

When using Angular 2, what distinguishes the following 2 options for passing a variable value to a style? Are there advantages and disadvantages, or is it simply a matter of personal preference, or is one more adaptable/meant for specific purposes? Option ...

Getting the content of a textarea within a v-for loop collection

Exploring this particular situation In a .vue file within the template <div v-for="(tweet, index) in tweets"> <div class="each_tweet"> <textarea v-on:keyup="typing(index)" placeholder="Share your thoughts">{{ tweet.c ...

What is the purpose of the forwardRef function in React?

I've been working on creating a HOC (higher order component) that assists in conditional rendering. Here is the snippet of code I have so far: interface ConditionalProps { renderIf?: boolean } const ConditionalizeComponent = <Props,>( Origi ...

How to use Typescript to find the length of an array consisting of either strings or

I am trying to determine the length of a string or array, stored in a variable with the data type var stepData : string | string[]. Sometimes I receive a single string value, and other times I may receive an array of strings. I need the length of the array ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

Error encountered: Unexpected character 'C' found at the beginning of the JSON data

Hey there, I'm new to all of this so just trying to figure it out! :) I stumbled upon a GitHub project that I really want to work on and understand in order to create my own solution. The project can be found at the following link: https://github.com ...

retrieve the index from the chosen elements

Hey there! I'm facing a situation where I have a div with several child elements. Using jQuery, I want to find the index of a specific element within a certain selector. <div> <div class="red"></div> <div class="red"></ ...

"Integrating FullCalendar with Cloud Firestore for seamless data management

Is It Possible to Integrate Observable with FullCalendar? I have a collection in Cloud Firestore and I want to display the data from this collection in real-time on FullCalendar. Although I know that using an Observable is necessary for this task, it see ...