Angular 7 continuously querying an API at regular intervals to retrieve response codes

I am currently working on creating a frontend GUI for an API. One of the key steps in this process involves polling an application for multifactor authentication. However, this particular aspect is not within my scope of work.

My objective is to develop an Angular 7 function that continuously polls or calls the HTTP GET /getmfa API every 5 seconds until the multifactor authentication is successfully completed and the API returns a JSON response.

I have encountered some challenges in getting the interval functionality to work properly. There seems to be a lot of conflicting information on the internet regarding the syntax for RxJS versions and the use of .pipe. I am using RxJS 6+ and Angular 7.

Initially, I attempted to implement the interval functionality with the following code:

    poll(apiUrl: string, options?: any): Observable<any> {
        let url = apiUrl;
        let headers = new HttpHeaders({
            'Content-Type': 'application/json',
        });
        let httpOptions = {
            headers: headers,
            withCredentials: true,
        };

        return interval(5000).pipe(map(() => {
            return this.http.get(url, httpOptions)
                .pipe(
                    map(
                        (data) => {
                            console.log('polling...');
                            console.log(data);
                            return data;
                        },
                        error => {
                            console.log('Error:', error);
                        }
                    )
                );
        }));

However, I found that even the timeout mechanism did not work as intended, but this approach was not aligned with my desired outcome anyway.

    poll(apiUrl: string, options?: any): Observable<any> {
        let url = apiUrl;
        let headers = new HttpHeaders({
            'Content-Type': 'application/json',
        });
        let httpOptions = {
            headers: headers,
            withCredentials: true,
        };
        setTimeout(() => {
            return this.http.get(url, httpOptions)
            .pipe(
                (data) => {
                    return data;
                }
            );
          }, 5000);

Could someone provide insights on where I might be making mistakes in my implementations?

Answer №1

To optimize your code, you should consider implementing a SwitchMap between the interval observable and the http observable.

  Use the following code snippet:

  return interval(5000).pipe(
      switchMap(counter => {
        return this.http.get(ulr, httpOptions)
          .pipe(
            catchError(error => this.handleError(error)
            )
          );
      })
    );

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

TS2307 error encountered in Angular 2 TypeScript due to the inability to locate a module for a private npm

I've been working on creating some components for internal company use, with the intention of sharing them through our private npm repository. However, I've hit a roadblock while trying to add these components to an app using npm and systemjs - I ...

Calculating the length of time based on a specific date in Angular 2+: A step-by-step

API: { data:{ "duration": 12, "startDate": "27-01-2020 16:09" } } I am currently working with Angular 2+. In the API response, the duration is set to 12 (in months) and the start date is provided as well... Task at hand: My goal is to ...

A TypeScript Record that allows for inferable value types

How can I construct a map that enforces the presence of all keys while still allowing the inference of the types of its values? If I have certain keys, for example: type State = "OPEN" | "CLOSED"; Method 1: using an untyped object con ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

The validation for the prop 'setLoading' is not defined

Currently, I am utilizing React version 17.0.2 along with Typescript for my project. My aim is to transfer the setLoading function from the parent component (App) to the child component (About) so that the loading state within App can be altered from About ...

Creating a single definition that encompasses the characteristics of both primitive and generic types without the need for combining them

Here is a scenario where I need to consolidate and refactor two types: ... .then((result1: any) => { let promises = { one: $q.when(val1), two: $q.when(val2) }; return $q.all(promises); }) .then((resolvedPromises: any) => { ...

Creating cohesive stories in Storybook with multiple components

I need assistance with my storybook setup. I have four different icon components and I want to create a single story for all of them instead of individual stories. In my AllIcons.stories.tsx file, I currently have the following: The issue I am facing is ...

In what way does Angular incorporate _page-theme.scss assets?

The Angular Material Documentation homepage includes a specific scss file: https://github.com/angular/material.angular.io/blob/master/src/app/pages/homepage/_homepage-theme.scss Although this scss file is not directly imported into the component's ...

working with JSON arrays in angular framework

Is there a way to print a specific value from an array in typescript? Below is the code snippet in typescript that I'm working with: import { AngularFirestore } from '@angular/fire/firestore'; export class ProfileComponent implements OnInit ...

Establish a public-facing link for a React component

After developing a React component that functions as a chatbot window, I am now looking for a way to make the opening button accessible across various websites and applications. My initial thought was to associate a URL with the button so that it can be ea ...

Using Typescript to pass inferred type to React's useCallback

Illustration: function useFunction(fn) { return fn; } type Data = { '/person': { person: any }, '/place': { place: any }, }; function useData<Path extends keyof Data>( path: Path, options: { callback?: (data: Data[ ...

Is there a way to remove an event listener once the associated button has been clicked within the given code?

Is there a way to prevent this event from triggering once the "dispensed" button is clicked in another module? Here is the code snippet: stopDrugOrder(e: Event, drugOrder: any, drugName: string) { const confirmDialog = this.dialog.open(SharedConfirmat ...

Event emitters from Angular 4 are failing to receive emitted events after the page is refreshed

Hey there, I'm facing an unusual issue with event emitters not functioning correctly during page refreshes. Here's the scenario: First, the user lands on the login page. Upon successful login, they are directed to the home page where I need spec ...

I am experiencing difficulties with broadcasting and attending events

File.js scope.menuItemClick = function (def, callbackText, keepMenuOpen) { console.log(def); if(def.automationId === "Print"){ console.log("before send"); $scope.$root.$broadcast("printingData","my Data"); console.log("after send"); } Nex ...

The data type 'string[]' cannot be assigned to the data type 'listData[]'

I'm currently developing a flexible component that allows the list view to be utilized by different components. However, the challenge arises from the fact that each component has a different data format. In my project, I'm unable to use type any ...

Leveraging interfaces with the logical OR operator

Imagine a scenario where we have a slider component with an Input that can accept either Products or Teasers. public productsWithTeasers: (Product | Teaser)[]; When attempting to iterate through this array, an error is thrown in VS Code. <div *ngFor= ...

How can I ensure that a list displaying data from an API is properly rendered in React.js using Vitest?

I have a component that displays a list fetched from a REST API using a useEffect hook without any dependencies. The fetched data is then stored in state. Here is the code snippet: import { useEffect, useState } from 'react'; import { fetchAllMed ...

Setting text in a datetime picker with ngx-mat-datetime-picker in an Angular application is a straightforward process

I've been utilizing the ngx-mat-datetime-picker library from angular-material-components to enable datetime selection. It's functioning effectively, but I'm searching for a way to insert text preceding the hour and minute inputs, such as &ap ...

Starting Out with Typescript Types - Unidentified term 'angular'

We are currently working on revitalizing an older AngularJS project by migrating it to .Net Core 3.1. As part of this process, we are looking to transition our scripts to TypeScript. While the project is functioning properly without TypeScript, we believe ...

Accessing clipboard contents upon button click using TypeScript

Seeking assistance with retrieving data from the clipboard in TypeScript after clicking on a button. Please provide guidance. Thank you! ...