What is the best way to consistently and frequently invoke a REST API in Angular 8 using RxJS?

I have developed a REST API that retrieves a list of values.

My goal is to immediately invoke this API to fetch values and store them in a component's member variable. Subsequently, I plan to refresh the data every five minutes.

Upon conducting some preliminary exploration, here is my approach:

Within my service class:

fetchFooList(): Observable<Foo> {
  return interval(FIVE_MINUTES).pipe(
    switchMap(() => this.http.get<Foo>(url, HTTP_OPTIONS))
  );
}

In addition, within my component:

fooItems: Foo[] = [];

ngOnInit(): void {
  this.loadData();
}

private loadData() {
  this._fooService.fetchFooList().subscribe(
    (fooItems) =>  this.fooItems = fooItems,
    (err) => console.error(err)
  );
}

The issue with this setup is that the initial API call is delayed until after the first five minutes elapse.

What are the alternatives for invoking the API immediately and then subsequently at five-minute intervals? I aim to avoid relocating the interval logic to the component class (as I prefer to maintain it in the reusable singleton service), as well as executing the API call once initially followed by setting up the interval (which seems unnecessary and overly duplicative).

Answer №1

Consider utilizing the timer function rather than interval:

return timer(0, FIVE_MINUTES).pipe(// etc
. (Note that the 0 represents the initial delay).

https://www.discoverrxjs.com/discover-rxjs/operators/creation/timer

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

Angular: Preserve the URL even when encountering a 404 page

Creating a custom 404 page in Angular 4 is something I have recently done, and I am looking for a way to preserve the incorrect URL that was input by the user. To see an example of this behavior, you can visit sites like GitHub. They show a 404 page when a ...

Angular 8 encountering issues with incomplete/impartial JSON parsing

Upon receiving a JSON object through a Socketio emit, the data appears as follows: { "single":[ { "name":"Xavi555", "data":[ { "_id":"5e2ea609f8c83e5435ebb6e5", "id":"test1", "author":"someone", ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

Access information through the restful api using the angularjs service $resource

I am attempting to utilize the $resource service with the surveygizmo API. Here is my code: HTML : <div ng-app="Survey"> <body> <div ng-controller="SurveyCtrl"> {{survey.data.title}} </div> </body> </div> My scr ...

Submitting form by double clicking and pressing enter at the same time

When using jQuery Validate to validate forms, I encounter a problem where double-clicking the submit button results in my application making two entries with the same data. This issue also occurs when pressing enter multiple times. Despite researching dif ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

Challenge with JWT Tokens

In my application, I am utilizing a Node.JS express backend along with an Angular 4 frontend. The user ID is stored in JWT tokens, which do not expire. Here is the scenario: The user logs in. A JWT Token is generated and signed (containing the user ID). ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

Deleting a specific row from a material table mat-table

Can anyone provide guidance on how to remove a selected row in mat-table using Angular? Please refer to the Stackblitz link provided below. https://stackblitz.com/edit/angular-qzh8g4?file=app/table-basic-example.ts I attempted to implement a solution, but ...

Choosing a Component in a Collection with Angular 2

Seeking advice on how to address an issue I'm facing with a sign-up page. Within the page, there are two buttons, represented by components <btn-gender>, each displaying a gender option for selection. The challenge lies in creating a logic to d ...

Unable to display image in jqGrid binary format

In our system, we use a standard function to retrieve images stored as binaries in the database, and this function works seamlessly throughout the entire system. However, when implementing jqGrid, I encountered difficulties using the existing structure as ...

node.js + typescript How can we access instances from methods?

Following a server rebuild, the compiler creates an instance in the included API controller as shown below: NewController.ts import express = require("express"); import INew = require("../interface/INew"); import New ...

The sequencing of operations in Node.js streams

I am having an issue with validating an image before saving it to disk. Currently, I am utilizing the GM library. // Express application implementation app.post('/image', function(req, res) { var stream = gm(req) .size({ bufferStr ...

Change the data returned by Ajax

After making an ajax request, my table gets populated with data from my array. The return is as expected, but now I want to modify this data before displaying it to the user. Whether this modification happens before or after the data is placed in the table ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

What is the most effective way to transfer a variable between two javascript files?

I am currently working on customizing the code from a github repository found at Github repo for integration with Google App Engine. However, I have encountered an issue when trying to pass a variable from /app.js to /books/crud.js. Although I have success ...

What is the process for sending an HTTP request within the Dialogflow -> Fulfillment environment?

When it comes to interacting with the API of my website to rectify the response for Google Assistant, I am facing some difficulties. 'use strict'; var requestNode = require('request'); const functions = require('firebase-function ...

Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...

What could be causing the Contact anchor element to not function properly?

I've been working on creating a dropdown menu for my API, but I'm having trouble getting the anchor links to function properly. I even attempted changing the "a" element to an onclick call with javascript:void(0) and added a function to open Gmai ...