Am I on track with this observation?

I am currently using the following service:

 getPosition(): Observable<Object> {
    return Observable.create(observer => {
        navigator.geolocation.watchPosition((pos: Position) => {
            observer.next(pos);
            observer.complete();
        }),
        () => {
            console.log('Position is not available');
        },
        {
            enableHighAccuracy: true
        };
    });
}

My intention was to utilize it in this way:

this.getLocationService.getPosition().subscribe((pos: Position) => {
        self._latitude = pos.coords.latitude;
        self._longitude = pos.coords.longitude; }

However, I encountered an issue where the expected behavior did not occur. I anticipated that whenever the position changes, the latitude and longitude values would also update simultaneously. Unfortunately, this does not happen as intended.

Answer №1

One potential problem arises due to the Observable contract

Understanding the Observable Contract

The concept of “The Observable Contract” can be found in various sources and documentation related to Observables, including the original Rx Design Guidelines from Microsoft that outlined the Rx.NET version of ReactiveX. This page serves as a summary of The Observable Contract.

Notifications

An Observable communicates with its observers through different notifications:
  • OnNext
    sends an item emitted by the Observable to the observer
  • OnCompleted
    signals successful completion of the Observable and indicates there will be no more items emitted
  • ...

Hence, if you wish to continue triggering events, refrain from calling the completed method

 getPosition(): Observable<Object> {
    return Observable.create(observer => {
        navigator.geolocation.watchPosition((pos: Position) => {
            observer.next(pos);
            // keep sending next without completing
            // until position is fully processed
            //observer.complete();
        }),
        ...

Answer №2

A comma out of place can cause quite a headache, it's important to properly manage the watcher when unsubscribing and pass any errors along to the observer.

public $getDeviceLocation():Observable<Position> {
    return Observable.create(observer => {

        const onSuccess:PositionCallback = (pos:Position) => {
            observer.next(pos);
        };

        const onError:PositionErrorCallback = (error) => {
            observer.error(error);
        };

        const options:PositionOptions = this.locationOptions();

        const watcher:number = navigator.geolocation.watchPosition(onSuccess, onError, options);
        return () => {
            navigator.geolocation.clearWatch(watcher);
        };
    });
}

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

Utilize an RxJS observable within a standard Express.js middleware function

Challenges arise as I navigate through RxJS in my project. The observable getSettings(req) is a crucial element that I wish to incorporate into a regular express.js middleware function, like so: middleware(req, res, next) { ... const settings = getSett ...

The React application is unable to communicate with my Express application in a production environment, despite functioning properly during development

Currently, I am attempting to make a basic get request to my express backend located at mywebsite.com/test. The expected response from the server should be {"test": "test"}. While this is working perfectly fine in development on localho ...

Evaluating the criteria and presenting two distinct notifications with setCustomValidity

When validating text fields in an HTML form, I am looking to check two conditions. Currently, the code below checks if the phone number entered is in the correct format and displays a message 'Enter a valid mobile number' if it is incorrect using ...

How to play audio with a source path that includes the special character "%" in JavaScript

Having an issue with playing an audio file that has '%' in its name. I've tried using the tag <audio src="test%320.mp3" controls></audio>, but it seems like the file is not being found when I try to play it. Can anyone ...

Using JavaScript to assign the title property to an <a> tag

I'm currently working on modifying a code snippet that utilizes jQuery to display the "title" attribute in an HTML element using JavaScript: <a id="photo" href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><i ...

Angular 2 Return {responseBody: "assigned variable with [object Object]"}

In my Angular 2 application, I am encountering an issue where I am sending a variable from a service to a component. In the template, the variable appears as expected, however, when attempting to send this variable to a PHP script using POST, I receive [ ...

I am looking to pair a unique audio clip with each picture in my collection

I have implemented a random slideshow feature that cycles through numerous images. I am now looking to incorporate a brief audio clip with each image, synchronized with the array I have established for the random pictures. The code snippet below is a simil ...

How to locate and extract specific data from a webpage table using JavaScript and Node.js for web scraping and storing in an array of objects

Exploring the realm of web scraping by targeting a UFC betting site for data extraction. JavaScript, alongside request-promise and cheerio packages, is utilized in this endeavor. Site: The primary aim is to retrieve the fighters' names along with th ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...

Highcharts introduces shared tooltips for specific data series

I am seeking to implement specific behavior in highcharts regarding tooltips. The desired setup includes having two types of tooltips: the default shared tooltip a custom tooltip For the custom tooltip, a simple formatter can be utilized. However, the c ...

Is it possible to extract specific columns from the Convex database?

I am looking to retrieve all columns from a table using the following code snippet. Is there a more efficient way to achieve this? I couldn't find any information in the documentation. Does anyone have a workaround or solution? const documents = await ...

The issue of Three.js Texture not displaying during loading

I'm currently working with Three.js in my Angular Application. I am attempting to display a cup (OBJ file) with a texture applied to it. The issue I am facing is that the texture only appears when I rotate or zoom the object. Otherwise, the object app ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

Adjust the size of the image within a designated container to decrease its proportions when there is an excess of text present

I am working on a project where I need to resize an image based on the available space within its container. When there is text in the description, the image should adjust its size accordingly without pushing the text upwards. I am using React for this pro ...

The scenario of two users simultaneously gaining control access in socket.io creating a race condition

There is a need to ensure that only one user at a time is notified for an available room. I am implementing a solution to prevent multiple users from being notified simultaneously for the same room. socket.on('Check', function (room) { io.in(r ...

What is the correct approach for detecting object collisions in Phaser 3?

Hey everyone, I'm facing a problem and could use some assistance. Currently, I am trying to detect when two containers collide in my project. However, the issue is that the collision is being detected before the objects even start moving on screen. It ...

Permanently dismiss Bootstrap 4 alert using a cookie

Recently, I came across a bootstrap 4 alert that I found quite useful. Here is the code snippet for it: <div class="alert alert-warning alert-dismissible fade show" role="alert"> <button type="button" class="clo ...

JavaScript Alert function doesn't wait for execution

I am facing an issue with my Signup page. After submitting the form, I use AJAX POST to send the data. The problem arises in the success function where an alert is triggered immediately without waiting for user input, leading to the execution of the next f ...

How can I set ion-option to be selected by tapping instead of having to click OK?

Currently, I am developing a mobile application and have encountered a scenario in which I utilized ion-option with ion-select, resulting in successful functionality. However, I am now aiming to remove the OK/CANCEL button so that users do not need to clic ...

Creating a Higher Order Component (HOC) for your Next.js page

Upon running the following code, I encountered an error message Error: The default export is not a React Component in page: "/" pages/index.tsx import React, { useState, useRef } from "react"; import type { NextPage } from "next&q ...