Acquire the map handler from the service

I'm finding this concept a little tricky to grasp.

retrieveLongitudeById(id: number | string) {
return this.getHoles().pipe(
  map(holes => holes.find(hole => hole.id === +id).lng)
  );
}

I want to access this method from my service and incorporate it into my geolocation component. Any advice on how to do that?

Haversine(): void {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( x => {

      this.myLat = x.coords.latitude;
      this.myLng = x.coords.longitude;

      this.courseLat = this._mont.getHoleLat();
      this.courseLng = this._mont.getHoleLng();


    console.log(`longitude: ${ this.courseLat } | latitude: ${ this.courseLng }`);
    console.log(`longitude: ${ this.myLat } | latitude: ${ this.myLng }`);


    const myCoords: GeoCoord = {
      latitude: this.myLat,
      longitude: this.myLng
    };

    const dominos: GeoCoord = {
      latitude: this.courseLat,
      longitude: this.courseLng
    };

    this.metres = this._haversine.getDistanceInMeters(myCoords, dominos);
    this.yards = this._haversine.getDistanceInYards(myCoords, dominos);
    this.kilometres = this._haversine.getDistanceInKilometers(myCoords, dominos);
    this.miles = this._haversine.getDistanceInMiles(myCoords, dominos);

    this.metres = this.metres.toFixed(2);
    this.yards = this.yards.toFixed(2);
    this.kilometres = this.kilometres.toFixed(2);
    this.miles = this.miles.toFixed(2);
 });
}

}

Update

export class Hole {
  constructor(public id: number, public name: string, public lat: number, public lng: number) { }
}

const HOLES = [
   new Hole(1, 'Hole 1', 1234567, -12345324)
  ];

I'm trying to retrieve these coordinates!

Answer №1

To utilize the service in your component, you must import it and inject it properly.

Within your <name>.component.ts file: import {YourService} from "servicePath";

export class NameComponent{
   // injection point
   constructor(private yourService : YourService){
     // call function here (or elsewhere)
     this.yourService.getHoleLng(id).subscribe(...)
   }
}

Alternatively, you can invoke it within a function:

Haversine(): void {
  // assuming id is 1 for demonstration purposes;
  let id = 1; // replace with desired id

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition( x => {

      this.myLat = x.coords.latitude;
      this.myLng = x.coords.longitude;

      forkJoin(
         this.yourService.getHoleLng.pipe(map( lng=> courseLng=lng)),
         this.yourService.getHoleLat.pipe(map( lng=> courseLng=lat))
      ).subscribe( ()=> {
           console.log(`longitude: ${ this.courseLat } | latitude: ${ this.courseLng }`);
            console.log(`longitude: ${ this.myLat } | latitude: ${ this.myLng }`);

         const myCoords: GeoCoord = {
           latitude: this.myLat,
           longitude: this.myLng
         };

         const dominos: GeoCoord = {
           latitude: this.courseLat,
           longitude: this.courseLng
           // latitude: this.courseLat,
           // longitude: this.courseLng
         };

         this.metres = this._haversine.getDistanceInMeters(myCoords, dominos);
         this.yards = this._haversine.getDistanceInYards(myCoords, dominos);
         this.kilometres = this._haversine.getDistanceInKilometers(myCoords, dominos);
         this.miles = this._haversine.getDistanceInMiles(myCoords, dominos);

         this.metres = this.metres.toFixed(2);
         this.yards = this.yards.toFixed(2);
      })    

}

It's crucial to wait for both lat and lng coordinates from your services before proceeding. Using the forkJoin operator ensures that both calls complete before further processing.

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

Is there a way to dynamically retrieve a JSON element in Typescript?

I am using a data grid throughout my application, and currently, I am retrieving the selected rowid with the following code. Here is the HTML snippet: <tbody> <tr *ngFor="let ddata of tableData.data; let i = index" (click)="setClickedRow(ddat ...

Footer missing from Tanstack React table

Library Version: "@tanstack/react-table": "^8.2.6", I have been attempting to include footers in my table without success. Despite setting static footer text with a fixed value, I am unable to render any dynamic values similar to how h ...

Encountered a mistake while trying to deploy an Angular 2 application on Heroku - received an error message indicating an expected expression but instead got

I am encountering an issue with my Angular 2 app. It runs perfectly fine locally, but when I deploy it on Heroku, I'm getting the following errors: >SyntaxError: expected expression, got '<' ><!DOCTYPE html> >shim.min.js ( ...

Using Angular: Embed environment.ts into index.html as a standalone JavaScript file

Angular is typically set up to include the environment.ts file into main.js during the build process. This means that when dealing with multiple environments and corresponding environment.ts files, we must choose the environment at build time. My goal is ...

Setting up "connect-redis" in a TypeScript environment is a straightforward process

Currently, I am diving into the Fullstack React GraphQL TypeScript Tutorial I encountered an issue while trying to connect Redis with express-session... import connectRedis from "connect-redis"; import session from "express-session"; ...

Talebook by Syncfusion

I'm completely new to Storybook and I am currently exploring the possibility of creating a Storybook application that showcases a variety of controls, including Syncfusion controls and other custom controls that I will be developing in the future. Ha ...

Using the jQuery val() Function with a User-Defined Object

I have a class named ValueBox with a custom val() method that I implemented as shown below: function ValueBox(params) { ... $.extend(true, this, $('/* some HTML elements */')); ... var $inputBox = $('input[type=text]', this ...

Using useEffect with promises causing TypeScript errors

useEffect(login, []) In this case, the login function returns a promise and the useEffect hook is triggered without expecting a return value. However, TypeScript shows errors like: Argument of type '() => Promise<void>' is not assi ...

React-aria | Encountering a typescript error with input fields/textfields

Seeking assistance with using react-aria, specifically the useTextField feature. Despite following the documentation available at , I encountered an error related to the input element. Any help would be appreciated. Code import { AriaTextFieldOptions, use ...

The error message "InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' in Angular 6 and Firebase" indicates a problem with the data being passed to the AsyncPipe in

**Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'. ** I am encountering a problem with unsubscribing from the observable. My Angular-cli version is 6.0.3 This is the HTML code in home.component.html <div class ...

Are the Angular App routerlinks functioning properly in development but encountering issues in the production environment?

Every time I execute the command npm start, my Angular application works perfectly as intended. However, when I attempt to build it in "prod" mode, my application doesn't seem to function properly. It only displays a static page. All navigation link ...

What is the best way to set up role redirection following a successful login within my MEAN stack application?

I have successfully developed a MEAN stack application with a functioning backend and frontend. However, I am looking to enhance it further by implementing role-based redirection after login. There are 5 roles in the system: admin, teacher, nurse, sportsma ...

Utilize the full path to load template/styles

What is the best way to load a component template and styles using absolute paths from another module? @Component({ selector: 'a-component', templateUrl: 'shared-module/components/another-shared-component/component.html', styleUr ...

AG-Grid hierarchical data structure

Transitioning from kendo tree list to ag grid tree data grid, I am facing a challenge. My table data is currently formatted as shown below, but ag grid requires data in the form of a string array of nodes in a tree. How can I adapt or customize my existing ...

The variable 'selectedvalue' is being accessed before it has been initialized

I'm currently working on sharing the date between components using BehaviorSubject, but I'm encountering an error in the process. public data = new BehaviorSubject<any>(this.selectedValue); public sharedData = this.data.asObservable(); sele ...

In search of captivating hover animations for Angular 6

Seeking Angular 6 animation code similar to this (hover scrolling). I have linked the jsfiddle below. Attempted in Angular 6 but encountering errors like "Cannot read property 'animate' of null," and "Cannot read property 'hover' of ...

Troubleshooting a CORS problem with connecting an Angular application to a Node server that is accessing the Spotify

I am currently working on setting up an authentication flow using the Spotify API. In this setup, my Angular application is making calls to my Node server which is running on localhost:3000. export class SpotifyService { private apiRoot = 'http://lo ...

Troubleshooting Issue: Data not appearing on Angular frontend when fetching from Laravel API

Utilizing Laravel for the back end and Angular for the front end development. The code segments related to Angular can be found in employee.component.ts file: import { Component, OnInit } from '@angular/core'; import { DataService } from 'sr ...

Upon executing the `npm start` command, the application experiences a crash

When I tried following the steps of the Angular quickstart guide, I encountered some errors after running "npm start". Here are the errors displayed: node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name 'Se ...

How do I increase a date by a specific number of days in Ionic 3?

ionViewDidEnter() { let self = this; self.originationsProvider.getOrigination() .then((data) => { self.origination = data; console.log(self.origination, "slefOrigination"); this.complete = self.origination.filter(( ...