What is the process for subscribing to setInterval() in an Angular application?

I'm currently working on developing an iOS location tracking application using the Ionic 5 Framework, Angular, and the Cordova Geolocation Plugin.

In the past, I was able to track user location changes using the watchPosition() function, which worked well on Android devices. However, I encountered issues with this functionality not working on iOS devices.

My new approach involves using the getCurrentPosition() function in conjunction with setInterval() to retrieve the current location and update it every one or two seconds.

Unfortunately, I'm now encountering the following error:

TypeError: this.watchLocationUpdates.subscribe is not a function

Does anyone have any suggestions on how to resolve this issue?


watchLocation() {
    const options = {
      maximumAge: 3600000,
      timeout: 5000,
      enableHighAccuracy: true,
    };
    this.isWatching = true;
    this.trackingId = '-' + Math.random().toString(36).substr(2, 28);

    // Please find relevant setInterval() part below
    this.watchLocationUpdates = setInterval(() => { this.geolocation.getCurrentPosition(options); }, 1000);
    this.watchLocationUpdatesSub = this.watchLocationUpdates.subscribe((resp) => {
        this.geoLocations = resp.coords;
        this.geoLatitude = resp.coords.latitude;
        this.geoLongitude = resp.coords.longitude;
        this.geoAccuracy = Math.trunc(resp.coords.accuracy);
        this.timeStamp = resp.timestamp;

        const position = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
        this.map.setCenter(position);
        this.map.setZoom(16);

        this.markers.map(marker => marker.setMap(null));
        this.markers = [];
        const latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
        const marker = new google.maps.Marker({
            map: this.map,
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 13,
                fillColor: '#1AA0EC',
                fillOpacity: 1,
                strokeColor: 'white',
                strokeWeight: 2
            },
            position: latLng
        });
        this.markers.push(marker);

        console.table('watchLocation function called', {
            trackingId: this.trackingId,
            latitude: this.geoLatitude,
            longitude: this.geoLongitude,
            accuracy: this.geoAccuracy,
            timeStamp: this.timeStamp,
            uId: this.uId
        });
        this.geolocationService.insertUserGeolocation({
            trackingId: this.trackingId,
            latitude: this.geoLatitude,
            longitude: this.geoLongitude,
            accuracy: this.geoAccuracy,
            timeStamp: this.timeStamp,
            uId: this.uId
        })
        .subscribe((response) => {
            localStorage.setItem('lastLocation', JSON.stringify({
                trackingId: this.trackingId,
                latitude: this.geoLatitude,
                longitude: this.geoLongitude,
                accuracy: this.geoAccuracy,
                timeStamp: this.timeStamp,
                uId: this.uId
            }));
            console.log(`user location data inserted in FB`, {
                trackingId: this.trackingId,
                latitude: this.geoLatitude,
                longitude: this.geoLongitude,
                accuracy: this.geoAccuracy,
                timeStamp: this.timeStamp,
                uId: this.uId
            });
        });
    });
}

Answer №1

One way to achieve this is by leveraging the interval() method in RxJS:

// Utilizing RxJS version 6 and higher
import { interval } from 'rxjs';

const timer = interval(1000);

timer.subscribe(/* add your custom logic here */);

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

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...

Troublesome GSP: JavaScript not functioning properly in Gr

I am experiencing an issue with the JavaScript code I have. Here's my code: <script type="text/javascript"><!-- ​$(function () { $('#add').click(function() { $(this).before($('select:eq(0)').clone()); ...

What is the best way to emphasize colors in search results?

Is it possible to assist in highlighting the searched words in yellow? Below is an example of code that filters words from the displayed data from a JSON feed URL. angular.module('sample', []). controller('sampleController', [' ...

Handling authentication errors in Angular 2 using @ngrx/effects

Everything is functioning smoothly with @ngrx/store and effects, but now I'm realizing that there will be a significant number of API calls (in effects). If any of those calls returns a 401 error, I need to redirect the user to the login page. The dil ...

Learn the method for type casting variables in Svelte 3 reactive syntax

I'm struggling with typing Svelte 3 reactive syntax variables. <script lang="ts"> import type { Player, Team } from "./types"; import { DEFAULT_PLAYER } from "./utils"; $: player = DEFAULT_PLAYER as Player; ...

Extracting information from WordPress JSON API using Ionic

Using JSON API, I am able to fetch data from WordPress in Ionic. However, I am facing an issue where only 10 data points are being retrieved at a time from the WordPress JSON API. What is the best way to fetch the next set of 10 posts with an on-screen lo ...

Creating a String-only pattern Validator: A step-by-step guide

Below is the code I've written: ***<input type="text" placeholder="First Name" name="firstName1" [(ngModel)]="firstName" #firstName1="ngModel" required pattern="^[a-z0-9_-]{8,15}$" >*** ...

modify brand information through the use of javascript and customizable settings

In the default setting, I want all product details to be displayed. If the option value matches the product's brand name (b_name), then I want to display the corresponding details. Let's consider a list of products with their details: Samsung ...

Step by step guide on inserting View and Delete buttons in an HTML table populated by JSON data

I've successfully loaded data from a JavaScript file in JSON format into a plain HTML table using JavaScript. Everything is working well so far. I now want to enhance the table by adding two buttons, View and Delete, that when clicked will redirect to ...

Implementing Basic Authentication for HTTP Requests in Angular 7

Currently, I am working with angular 7 along with Spring Boot and Spring Security. Within the Back End, I have successfully implemented basic authentication. However, while attempting to send a request from Angular with an Http Header that includes User n ...

Tips for Utilizing PHP Without the Need to Refresh the Page

Below are the contents of three files with their respective code: Controler.php <iframe id="frame1" style="display:none"></iframe> <iframe id="frame2" style="display:none"></iframe> <button onClick="document.getElementById(&apo ...

Stop the submission process by deactivating the button until a selection is made

Is there a way to prevent the submit button from being clicked until the user has selected or typed at least one value? <form name="forma" method="POST" action="used-results.php" id="apliforma"> many textboxes and dropdown menus <a oncli ...

Retrieve the live value for plugin settings following the completion of DOM loading. (Fineuploader plugin)

I am seeking assistance with a situation. I am utilizing Fineuploader and I need to access and transmit the value of an input field (which will serve as the file group title). To achieve this, I am using the path to a server-side script (as I did not wri ...

Explore within the attribute of a JSON

Here is the JSON structure: var parse = [ { "variation_id":"34", "attributes":{ "attribute_pa_rozmiar":"m" }, "image_src":"http://localhost/Fraise-WP/wp-content/uploads/2013/06/Jellyfish-300x300.jpg", "image_l ...

What is the best way to input data into nedb across various lines?

There is a requirement to store each element of an array into separate lines while saving it in the NEDB database. The idea is to add "\r\n" after every element, like this: Currently, I am doing the following: usernames = ["name1","name2","name3 ...

Obtain the input value from a modal and receive an empty string if no value

Utilizing ng-multiselect-dropdown within my bootstrap modal allows users to choose multiple products. Each time an item is selected (onItemSelect), a new div is inserted using the jQuery method insertAfter(). This new div displays the quantity of the selec ...

AngularJS enables seamless two-way data binding with DropDownList in the Model-View-Controller (M

As a beginner in AngularJS, I am currently experimenting with implementing 2-way data binding for the Gender Dropdown menu similar to what I have done with textboxes. Below is a snippet of code for the dropdown control: <div class="form-group"> ...

If the div element undergoes a change, use an if-else condition to populate the data fields accordingly

I'm looking to create a basic if/else statement in JavaScript that checks if a div element has changed before populating JSON data fields/variables that pull from dynamically updated HTML. I want to avoid using the deprecated DOMSubtreeModified metho ...

Using Angular 2 to bind to a formControl in a Select2 multiple selection scenario

I have been working on implementing Select2 in my Angular2 application. While I am able to display my selection when choosing the options, I am facing an issue with binding the selected options to my Angular form control. Below is the code snippet from my ...

Add a JSON file containing an image path as a value into a CSS background property

I currently have a MongoDB database containing documents with 'img' values structured as follows: "img": "../folder/img.jpg" Would it be feasible to utilize this string in my CSS for modifying the background image? This is essential because I n ...