Exploring ways to test the ng-web-apis/geolocation Observable within an Angular 8 environment

I'm currently working on testing a basic Angular 8 service that utilizes the GeoLocation Service from Web APIs for Angular, which can be found at this link.

 public enableGPS() {
    if (!this.locationSubscription)
        this.locationSubscription = this.geoLocationService.subscribe(
            (position) => {
                this._currentLocation = position.coords;
            }
        );
 }

Below is an example of the test:

 describe("Toggle Location Service", () => {

    it("should enable location service", () => {

        const testPosition = {
            position: {
                coords: {
                    longitude: 1.0,
                    latitude: 2.0
                }
            }};

        let geoLocationService: GeolocationService = TestBed.get(GeolocationService);
        spyOn(geoLocationService, 'subscribe').and.returnValue(
            Observable.of(testPosition));
        service.enableGPS();
        expect(service.currentLocation).toEqual(testPosition);
      });
    });

However, I've been encountering an issue where service.currentLocation remains undefined and the subscription callback never triggers.

Answer №1

Perhaps it's not too late to address your inquiry, as I recently found myself in need of implementing this for my own project.

To avoid further prolonging the issue and since I faced difficulties making the library work, I opted to utilize the browser's resources directly instead.

https://developer.mozilla.org/en/docs/Web/API/Geolocation/getCurrentPosition

The service I developed looks like this:

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class LocationService{
    constructor(){
    }
    
    getPosition(): Promise<any> {
        return new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(resp => {
                    resolve({lng: resp.coords.longitude, lat: resp.coords.latitude});
                },
                err => {
                    reject(err);
              });
        });
    }
}

Subsequently, I implement it in my component as follows:

import { LocationService } from '../Interfaces/Services/location.service';

  location : any = { latitude: '', longitude: '' };
  constructor(
    private _locationService: LocationService
  ) {

  }
  async getLocation() {
    this._locationService.getPosition().then(pos => {
        this.location= {
          latitude: pos.lat,
          longitude: pos.lng
        }
    });
  }

I trust that this information proves useful to you. If not, I hope it provides clarity for upcoming developers.

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

"Exploring the world of Typescript with the Drawflow library

Currently, I am integrating the fantastic Drawflow library created by @Jerosoler (available at: https://github.com/jerosoler/Drawflow) into my PrimeNg project. User @BobBDE has provided typescript definitions for this library here: https://www.npmjs.com/p ...

Move the files created by ng build in the specified output directory to a different location

I am facing an issue with my Angular project. Whenever I run the ng build command, the build artifacts are generated in the dist folder as we have specified "outDir": "dist" in angular-cli.json. However, I then have to manually copy these files from the di ...

What is the best way to retrieve the file path of a imported Angular module?

I am trying to figure out how to retrieve the path of the BarComponent within the code snippet below. Specifically, I need to obtain '../bar/bar.component'. When dealing with a module loaded from a package such as Component module, I would like t ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

What is the best way to restrict the suggested values in a property depending on the value of another property?

I'm working on creating a third interface that depends on the value of properties from two other interfaces, while also introducing a unique third property. I've chosen not to extend the third property from the first two interfaces as it may not ...

When I try to use http-server with the port 8080, my Angular application is not being served. However, when

Upon opening my localhost, this is the view I encounter My goal is to create a Progressive Web App (PWA) using Angular. I meticulously followed the guidelines outlined on the angular.io site, yet it does not display the standard "Welcome to your app" page ...

Accessing the map in an Angular 6 service via Leaflet

Embedding a map into my Angular 6 app service has been a bit tricky. Currently, I'm passing it as an argument when calling an init function in the service and providing it via Subject from the component after fetching data from the store. However, som ...

RxJS: Ensure Observables emit values sequentially, waiting for the completion of the previous Observable

In my current project, I have been working on implementing a unique Angular structural directive. This directive is designed to read and store the text content of an HTML element along with all its children, remove the contents upon AfterViewInit, and then ...

The data from Angular2 Observable Subscription appears undefined, although a closer look at the Browser Debug reveals otherwise

Is it possible there is an issue with the data subscription process? Upon subscribing to data from a service call, 'undefined' is returned as the data set. Surprisingly, when I debug the code in the browser, it clearly shows that the correct dat ...

Component fails to navigate to the page of another component

Hello there. I am facing an issue where the button with routelink in the RegistrationComponent is not routing to the page of LogInComponent and I cannot figure out why. Angular is not throwing any errors. Here is the RouteComponent along with its view: im ...

Angular's forEach function seems to be stuck and not loop

I'm attempting to cycle through a list of objects in my Angular/Typescript code, but it's not working as expected. Here is the code snippet: businessList: RemoteDataSet<BusinessModel>; businessModel: BusinessModel; this.businessList.forE ...

Tips for deploying an Angular Universal 9 application on a live server

Our Angular 9 app functions perfectly when deployed on an IIS server. We also have a version of the app that has been integrated with Universal by another company. Now, we need to figure out how to deploy our app with server-side rendering into productio ...

Angular 6 Integration: Configuring CORS and JWT in Spring Boot

While working on my Spring Boot app with JWT, I encountered a CORS error when attempting to login from the Angular 6 client. Access to XMLHttpRequest at 'http://localhost:8082/login' from origin 'http://localhost:4200' has been blocked ...

What is the best way to communicate an event occurring within the ng-content to the reusable parent component in Angular?

I am looking to create a versatile dropdown component in Angular that can display different content such as a list or a tree. Essentially, I want to be able to extract the selection label that triggers the dropdown to open and close upon clicking. dropdow ...

The anticipated outcomes are not achieved when utilizing environmental variables in Angular 2

Is it expected that when we use ng serve --env=prod, it should work with the values set in environment.prod.ts? Well, in my experience, it doesn't seem to be working as expected as I always receive the values from environment.ts (which is the developm ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

Looking for guidance on integrating REST API consumption features into Ionic Framework 3.x?

It's been a long time since I last used the ionic framework. The version I worked with was 1, where every page created with Ionic Creator had its own controller for adding JavaScript code to consume my REST framework. Now that I've downloaded th ...

Implementing computed properties: A guide to incorporating type setting

I currently have two separate interfaces defined for Person and Dog. interface Person { name: string; weight: number; } interface Dog { name: string; mass: number } const specificAttribute = isDog ? 'mass' : 'weight'; ...

The button click function is failing to trigger in Angular

Within my .html file, the following code is present: The button labeled Data Import is displayed.... <button mat-menu-item (click)="download()"> <mat-icon>cloud_download</mat-icon> <span>Data Imp ...