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

Creating automatic page additions using Node.js on Heroku?

Can you assist me with a challenge I'm facing? Currently, I am using node.js and heroku to deploy an application and each time I add a new post, I have to manually update my web.js file. This process was manageable when I had fewer pages, but now it&a ...

"Transforming a query into a JSON array - a step-by-step

My query generates the following output: { key:1,label:"R. Bulan"} { key:2,label:"R. Bintang"} { key:3,label:"R. Akasia"} { key:4,label:"R. Guest Room"} This is my SQL query: select '{ '||'key:'||IDMEETINGROOM||''||',l ...

Ajax: Why am I receiving an error response instead of a successful one?

It's puzzling why my code is triggering the error function instead of success. The console.log keeps showing me this: Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: f ...

Ionic 2 encountering issue with `ctorParameters.map` not being a function error

Recently, I wanted to incorporate the Network-information plugin into my project but encountered compatibility issues with an older version of Ionic-native. To resolve this, I took the following steps: npm rm --save ionic native npm install --save ionic-n ...

Is there a way to eliminate the legend symbol for just one legend in Highcharts?

Looking to customize a legend in Highcharts but facing limitations due to Plot Lines and Bands not having legends. To work around this, I have added an empty series that acts as a toggle for showing/hiding plot lines. Since my plot lines are vertical, I im ...

The server-side PHP script may not always successfully respond to an Ajax call from the client

Whenever I try to access my index.html site, there are times when the Ajax request is made to call the PHP on the server in order to display the dynamic content. But for some reason, it only works intermittently when I manually refresh the page using the a ...

When using create-react-app, the value of 'process.env.NODE_ENV' can be accessed as either a string or a process object during runtime

Have you come across code that looks like this: if(process.env.NODE_ENV === 'development') { // Perform operations specific to DEVELOPMENT mode } Similarly, you might see process.env.NODE_ENV === 'production. When we run npm run ...

What is the best way to fill a list-group using JavaScript?

Fetching ticket data from a controller is done using the code snippet below: $.ajax({ type: "GET", url: "/Tickets/List/", data: param = "", contentType: "application/ ...

What could be causing Jquery's $.ajax to trigger all status codes even when the call is successful?

Here is a simple Jquery ajax function call I have. function fetchData(){ var jqxhr = $.ajax({ url: "../assets/js/data/users.json", type: "GET", cache: true, dataType: "json", statusC ...

Utilize Material-UI in Reactjs to showcase tree data in a table format

I am currently tackling a small project which involves utilizing a tree structure Table, the image below provides a visual representation of it! click here for image description The table displayed in the picture is from my previous project where I made ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

The incorrect type is being assigned to an array of enum values in Typescript

Here's some code that I've been working on: enum AnimalId { Dog = 2, Cat = 3 } const animalIds: AnimalId[] = [AnimalId.Dog, 4]; I'm curious as to why TypeScript isn't flagging the assignment of 4 to type AnimalId[]. Shouldn't ...

Does Chrome have a feature that disables event listeners?

I'm currently working on a tool that incorporates file drag and drop functionality. Strangely, this feature works perfectly in all browsers except for Chrome. Surprisingly, however, it does work in Chrome when the tool is run locally. Here is the cod ...

"Learn how to dynamically change the color of a button in Angular after it has been clicked

Can someone assist me in changing the button color to red after it has been clicked? I am looking for guidance on how to achieve this. The current code snippet is as follows: <td> <button mat-icon-button color="primary"> <m ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

Why won't the div move when I click it?

Could you please explain why my JavaScript code isn't functioning as expected? The intended behavior is for the 'mark' div to move to the current mouse coordinates upon clicking within the map. ...

In Node.js and Postgresql, encountering the error "Trying to access a property that is undefined" is common and can be frustrating

const pool = new pg.Pool(config); var tablename = req.body.tablename; pool.connect(function (err, client, done) { var query_get_value = 'SELECT * FROM '+ tablename; client.query(query_get_value, function (err, result) { d ...

'This' loses its value within a function once the decorator is applied

Scenario: Exploring the creation of a decorator to implement an interceptor for formatting output. Issue at Hand: Encountering 'this' becoming undefined post application of the decorator. // custom decorator function UseAfter(this: any, fn: (.. ...

How does Vue handle the situation when the value of an input field does not match the bound "data"?

Before diving into the intricacies of v-model, I want to take a closer look at how v-bind behaves. Let's analyze the example below: <div id="app"> <input type="text" :value="inputtedValue" @input ...

Removing AWS-CDK Pipelines Stacks Across Multiple Accounts

Currently, I am utilizing pipelines in aws-cdk to streamline the process of automating builds and deployments across various accounts. However, I have encountered an issue where upon destroying the pipeline or stacks within it, the respective stacks are ...