What is the best way to obtain real-time data from a database in Angular without the need to constantly refresh the page

I'm currently working on a project using Angular, with my database in MongoDB and backend in Flask. I have a collection where the data is constantly changing every 10 seconds. I am developing REST APIs to facilitate sharing data between Angular and MongoDB. How can I ensure that I always have the most up-to-date information from my database without having to refresh the page each time?

The values for heart rate, blood pressure (BP), oxygen levels (O2), and pulse rate (PR) are all updated every 10 seconds in this section.

  <ng-template #not_distressed>
                <div class="card-header" style="color: rgb(0, 0, 0); ">
                  <b>Ward No : {{patient.ward_no}}</b>
                </div>
                <div class="card-body" style="color: rgb(0, 0, 0); ">
                  <div style="text-align: left;"></div>
                  <div style="text-align: right;"></div>
                    <h5 class="card-title"><b>Name : </b>{{patient.patient_name}}</h5>
                    <p class="card-text">
                      <b>Heart beat : </b>{{patient.heart_rate}}<br>
                      <b>B.P. : </b>{{patient.BP}}<br>
                      <b>O2 : </b>{{patient.O2}}<br>
                      <b>P.R. : </b>{{patient.RR}}
                    </p>
                </div>
              </ng-template>

TypeScript file

        import { Component, OnInit } from '@angular/core';
    import { PatientVitalsService } from '../services/patient-vitals.service';
    @Component({
      selector: 'app-patient-vitals',
      templateUrl: './patient-vitals.component.html',
      styleUrls: ['./patient-vitals.component.css']
    })
    export class PatientVitalsComponent implements OnInit {
    
      public patientVital={};
    
    
      constructor(private _patientListService: PatientVitalsService) { }
    
      ngOnInit() {
        this.dataService.getdetails().subscribe((data: any)=>{
    console.log("In service",data);
    this.repos = data;
    this.patientVital = this.repos['result']
  })  
      }
    
    }

Service.ts file

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, Subject, throwError, BehaviorSubject } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

@Injectable({
  providedIn: 'root'
})
export class DataService {
      get_symptoms = "http://127.0.0.1:5000/api/getdetails"

getdetails(): Observable<any> {
    return this.httpClient.get(this.get_details)
  }
}

Answer №1

To create a continuous data polling system, you can enhance your current function by integrating it with the timer feature in RxJs. Instead of simply returning a value, utilize switchMap operator to return the desired data. You can also implement additional operators for increased reliability and functionality.

import { Subject, timer} from 'rxjs';
import { switchMap, share, retry, takeUntil } from 

export class DataPoller {
  fetchDataUrl = "http://127.0.0.1:5000/api/getdetails"
  private stopPoll$: Subject<boolean> = new Subject<boolean>();

  getData(): Observable<any> {
    this.stopPoll$.next(false); // Reset stopPoll$ as needed
    // Initiate at 1st millisecond, repeat every 10 seconds
    return timer(1, 10000).pipe(
      switchMap(() => this.httpClient.get(this.fetchDataUrl)), // Retrieve data
      retry(), // Retry if unsuccessful
      share(), // Share -> prevent creating new subscriptions on each subscribe
      takeUnitl(this.stopPoll$) // Enable stopping the poll when necessary
    )
  }

  stopPolling(): void {
    this.stopPoll$.next(true);
  }
}

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

The Mat table is not updating on its own

I am facing an issue in my Angular application where a component fetches a hardcoded list from a service and subscribes to an observable to update the list dynamically. The problem arises when I delete an element from the list, as it does not automaticall ...

What is the best way to end a Google OAuth session using Firebase on an Ionic 2 application?

My Ionic 2 app integrates Google Authentication using Firebase. I have implemented a logout button within the app that calls the Firebase unauth() method. However, this only disconnects the Firebase reference and does not terminate the Google OAuth session ...

When using a custom structural directive, it may not function properly if the selector name does not exactly match

I have created my own custom structural directive in Angular import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[ttIf]' }) export class AppHighlightStrucDirect ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

Using inline style instead of relying on the quill editor's built-in classes, as classes may not be accessible in order to render HTML effectively

I have integrated the ngx-quill editor into my Angular project as the rich text editor. I plan to save the generated HTML in a database and display it on various browsers using innerHTML. Since the styling is done through a class attribute that references ...

The NgZone reference error caused the prerendering to fail

I am facing challenges with the implementation of NgZones. Despite defining NgZone, I keep encountering this error: "NodeInvocationException: Prerendering failed because of error: ReferenceError: NgZone is not defined" Below is my app.error-handle.ts file ...

Setting up Firebase App Check in an Angular projectWould you like to know

I have a question about initializing Firebase app check with Angular. I am currently using AngularFire, but I'm not sure how to initialize Firebase app check before using any services. The documentation provides the following initialization code to b ...

Changing Array Object into a different Array Object (with Angular)

I am dealing with an array Object [ { product: "Product A", inStock: 3, onHold: 1, soldOut: 2 }, { product: "Product B", inStock: 2, onHold: 0, soldOut: 1 }] I am struggling to convert it into the new array format below. Any assista ...

Tips for avoiding the error message "Expected 1 arguments, but got 0" when the specified argument is actually `undefined`

Current Typescript Version: 2.6.2 I am in the process of enhancing the type safety of redux beyond what is provided by default typedefs, while also streamlining some of the redundant code. I believe I am edging closer to my desired setup, with just one is ...

Enable encryption for data stored in MongoDB to enhance security

I successfully configured a 3 node MongoDB 3.2.3 Cluster on RHEL 7. Given that encryption is a new addition to this MongoDB version, I experimented with various methods to enable it in my configuration file. Below, I am sharing a snippet from my configura ...

Bi-Directional Reference with Repository Method in Doctrine ODM OneToOne Mapping

Is it possible to utilize Doctrine ODM for establishing a one-to-one bi-directional reference that lazy loads while utilizing a field other than the primary key for the reference? In my MongoDB database, I have two document collections: Article and Articl ...

Using JSON for exporting data - a comprehensive guide

First off, I want to express my gratitude for all the support you have provided. I have a question regarding the use of JSON. From what I understand, JSON is used to retrieve data from a database and display it on an HTML page, or even export the data to ...

Changing the position of the custom tooltip in Ag-grid

Is there a way to adjust the placement of my custom tooltip? I want it to always appear in the upper right corner of the table, rather than below the cursor. Here is an example of how it currently displays: pic1 I have a specific image of how I would like ...

Incorrect character set used in jsonp ajax requests

My ajax request implementation looks like this: function apiCall(resource, data, callback) { if(data == undefined || data == null) data = {}; $.ajax({ dataType: 'jsonp', data: data, url: nodeUri + "/" + resource }). ...

What is the best way to simulate a MongoDB client during the testing of a Next.js page API using Jest

Currently, I am running tests to test a page's API file with jest. While the tests are running fine, there are some issues that I am encountering. Each Page API POST request being made is sending data to the mongo database, even during test runs. Thi ...

When updating a user profile on Angular, the application automatically redirects to the main page

I am faced with a puzzling issue regarding two components: home and admin. In the home component, I have the capability to create, delete, and edit posts. Similarly, in the admin component, I perform similar tasks but with a different database collection ( ...

Traverse a nested array containing children elements to construct a pathway map

I am currently working with a multidimensional array that contains children (subcategories): As I am setting up Angular routing, I receive this data format from an API. const items = [{ displayName: 'News', urlName: 'news', subca ...

An advanced API utilizing JSON Hypermedia, featuring interactive forms and interconnected links

As I begin the initial stages of planning a RESTful API, my aim is to ensure it adheres to the HATEOAS constraint of REST. However, I also want to provide the API in JSON format. My query revolves around whether there are existing conventions for represent ...

Creating a Reliable API Response Structure with Laravel and Dingo

As I work on developing a series of REST APIs for mobile apps, my approach involves utilizing the repository pattern within the Laravel project. A key aspect that I am looking to implement is the integration of a presenter and transformer to ensure consist ...

A new concept within the realm of programming is the Export class statement that utilizes

Is it possible to define both a class and an interface in the same file and export the class directly without any issues? I have encountered problems when using export default Foo, as it exports as { default: Foo } instead of the actual class object. I am ...