What are the steps to save information to Firebase's Realtime Database?

Currently, I am facing an issue where user location data is not being written into our Firebase Realtime Database even though the console confirms that the data is fetched correctly every 2 seconds.

I am seeking assistance on how to resolve this problem.

tracking.page.ts

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

    clearInterval(this.interval);
    this.interval = setInterval(() => {
    this.watchLocationUpdates = this.geolocation.getCurrentPosition(options);
    this.watchLocationUpdates.then((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;

      this.geolocationService.insertUserGeolocation({
        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
            });

      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);
      });
    }, 2000);
}

geolocation.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment  } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class GeolocationService {
  databaseUrl = environment.firebase.databaseURL;

  constructor(private http: HttpClient) {
    console.log('Hello OrganizationService Provider');
    console.log('OrganizationService: ', this.databaseUrl);
  }

  insertUserGeolocation(data) {
    return this.http.post(`${this.databaseUrl}/geolocations/.json`, data);
    console.log('insertUserGeolocation(data): this.insertUserGeolocation(data));
  }

Answer №1

If you want to streamline your process and make it more effective, consider utilizing the library AngularFire instead of relying on the HttpClient for http requests.

With AngularFire, adding data is simple using the push() method:

const itemsRef = db.list('items');
itemsRef.push({ name: newName });

Check out this link for installation instructions: https://github.com/angular/angularfire/blob/master/README.md#install

Answer №2

I have successfully discovered the solution. You can see the code snippet below.

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 Firebase`, {
            trackingId: this.trackingId,
            latitude: this.geoLatitude,
            longitude: this.geoLongitude,
            accuracy: this.geoAccuracy,
            timeStamp: this.timeStamp,
            uId: this.uId
            });

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

Asynchronous function in TypeScript is restricting the return type to only one promise type

Using node version 14.7.0, npm version 6.14.7, and typescript version 3.7.3. I have a function that interacts with a postgres database and retrieves either the first row it finds or all results based on a parameter. It looks something like this: async fet ...

"Encountered an ENOENT error message following the deployment

I'm really hoping for some insight into the current situation. Deploying an Angular 7 / .Net Core 2 application to Azure is giving me trouble. I am utilizing the publish profile provided by Azure in Visual Studio. Everything runs smoothly when testi ...

"Is there a way to transmit a Firebase error message from a service to a controller

In my development work, I utilize Angular js and firebase. Specifically, for handling login and register forms, I have created a controller named "userController" which calls functions in my userProvider service. One challenge I faced was how to display f ...

What is preventing me from running UNIT Tests in VSCode when I have both 2 windows and 2 different projects open simultaneously?

I have taken on a new project that involves working with existing unit tests. While I recently completed a course on Angular testing, I am still struggling to make the tests run smoothly. To aid in my task, I created a project filled with basic examples f ...

How to Avoid the "Expression Changed After it has been Checked" Error?

I understand the reason behind the Expression Changed After it has been checked error, however, I am struggling to find a solution to prevent it. Situation Within my Component, there is an ngxDatatable that we manipulate to adjust its width based on cert ...

Angular Chart.js is throwing an error: "Uncaught SyntaxError: Cannot use import statement outside a module"

Upon opening the page, an error in the console related to Chart.js 4.2.1 is being displayed. Description of first image. Description of second image. Is it possible that this issue solely lies with Chart.js? How can it be resolved? To address the proble ...

Is there a way to both add a property and extend an interface or type simultaneously, without resorting to using ts-ignore or casting with "as"?

In my quest to enhance an HTMLElement, I am aiming to introduce a new property to it. type HTMLElementWeighted = HTMLElement & {weight : number} function convertElementToWeighted(element : HTMLElement, weight : number) : HTMLElementWeighted { elemen ...

Conditional ng-select dropdown functionality

I am seeking a way to showcase the purchaseOrderStatusName within a NgSelect dropdown. The API offers various status values, including: OPEN, RECEIVED, CANCELLED. TS file: RetrieveAllPurchaseOrders() { this.purchaseOrderService.getAllPurchaseOrders ...

A guide on utilizing the TypeScript compilerOptions --outDir feature

Recently, I encountered an error message from the compiler stating: Cannot write file 'path/file.json' because it would overwrite input file. After some investigation, most of the solutions suggested using outDir to resolve this issue. Although t ...

The Radio Button's value appears in a distinct way on Ionic Angular

I am currently working with the Ionic framework and I am trying to display data values on radio buttons. However, I am facing difficulties in retrieving the correct value and setting it appropriately. index.html <td> <label>{{learn ...

Encountering TypeError with Next.js and Firebase: Unable to access properties of undefined (specifically 'apps')

My goal is to create an authentication system using NextJS and Firebase. The issue I am facing is in my firebaseClient.js file, where I am encountering the error "TypeError: Cannot read properties of undefined (reading 'apps')". Here is a snipp ...

Finding the root directory of a Node project when using a globally installed Node package

I've developed a tool that automatically generates source code files for projects in the current working directory. I want to install this tool globally using npm -g mypackage and store its configuration in a .config.json file within each project&apos ...

Angular Typescript subscription value is null even though the template still receives the data

As a newcomer to Angular and Typescript, I've encountered a peculiar issue. When trying to populate a mat-table with values retrieved from a backend API, the data appears empty in my component but suddenly shows up when rendering the template. Here&a ...

issue with Firebase notifications not triggering in service worker for events (notification close and notification click)

I've been working on implementing web push notifications in my React app using Firebase. I've managed to display the notifications, but now I'm facing two challenges: 1. making the notification persist until interacted with (requireInteracti ...

Displaying [object Object] in Angular Material datatable

I am currently working on implementing a datatable component using Express and Firebase DB. Below is the service request data: getText() { return this.http.get<nomchamp[]>(this.url) .map(res => { console.log(res); return res }); ...

Explore lengthy content within Angular 2 programming

I have a lengthy document consisting of 40000 words that I want to showcase in a visually appealing way, similar to HTML. I aim to include headers, paragraphs, and bold formatting for better readability. Currently, I am developing an Angular application. D ...

What is the best way to hide the back arrow in Cordova UWP for Ionic 4?

I am currently developing a Windows 10 (UWP) application using Ionic 4 (Angular). I want to remove the back arrow from the interface: Example of back arrow I have attempted various solutions, such as implementing in the app.component constructor with in ...

Tips for navigating back to the previous component in React:

Greetings! I'm currently working on a simple CRUD example using React.Js and TypeScript. In my project, I have set up the following component hierarchy: -FetchNaselje --Modal ---AddNaselje It's structured such that AddNaselje is a child of Moda ...

Exploring the depths of Angular2 RC6: Implementing nested modules and routing

Within my application, I have a module called SupportModule which consists of 3 sub-modules: AdminModule, ChatModule, and ContactModule. Each of these modules has its own defined routing structure. The overall structure resembles something like this: htt ...

Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'. The specific error message states: "Error: There is no Form ...