The HTTP GET request will not be duplicated or executed until another request is made

Having trouble polling data with a GET request from the API. I want to poll data every 1 second for up to 30 seconds. The issue is, angular appears to be sending requests (logging responses), but doesn't actually send a request to the server.

Here are the methods I wrote in my service:

private pollStatus(token: string, remember: boolean):Observable<any> {
  const httpOptions = {
    headers: new HttpHeaders({
      'Token': token,
      'Remember': '' + remember
    })
  };
  const url = 'auth/status';

  return this.http.get<any>(url, httpOptions).pipe(map(response => {
    console.log('polldata', response.status);
    return response;
  }));
}

public secondFactor(token: string, remember: boolean): Observable<any> {

  let pollData$ = this.pollStatus(token, remember);

  let watchdog = timer(30 * 1000);
  // this.http.post<any>('/auth/login', {}).subscribe();

  return Observable.create(subject => {
    let pollSubscription = pollData$.pipe(expand(_ => timer(1000).pipe(concatMap(_ => pollData$))), takeUntil(watchdog)).subscribe(response => {
      console.log('secondFactor', response.status);
      // some action based on the response is performed here
    });
  });
}

Calling the component like this:

public ngOnInit(): void {
    this.authService.secondFactor(this.authyToken, true).subscribe(response => {
      console.log('response in component', response);
    });
}

In the console, I see that the GET request subscription is happening multiple times (code:

console.log('polldata', response.status);
is executed). However, only one request is actually made to the server (confirmed on the back-end and in the network tab).

Console output:

polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending

etc. etc. etc.

Tested this behavior on different browsers (Safari & Chrome) - same issue.

Work-around:

Discovered that if I send a POST request to the server (commented line:

// this.http.post<any>('/auth/login', {}).subscribe();
in the secondFactor() method), then Angular starts performing GET requests more than once.

Answer №1

Could you please verify if this code snippet is correct:

function performSecondFactorAuthentication(token: string, remember: boolean): Observable<any> {
    let pollData$ = this.pollStatus(token, remember);

    let watchdog = timer(30 * 1000);

    return interval(1000).pipe(
        takeUntil(watchdog),
        concatMap(() => pollData$),
        tap(response => console.log('Performing second factor authentication', response.status))
    );
}

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

To access the Angular application using oidc-client.js, users must first login in a separate tab

My Angular 8 application is using authorization handled by (oidc-client.js) + .Net Core IdentityServer4. Although everything seems to be working fine, I encounter an issue when opening the same application in a second tab - it requires me to login again. ...

Utilize @db.Decimal within the Prisma framework for the parameters "s", "e", and "d"

When I define the schema in Prisma like this: value Decimal? @db.Decimal(7, 4) Why do I always get this format when retrieving the value from the database: "value": { "s": 1, "e": 0, & ...

Retrieving a nested type based on a particular condition while keeping track of its location

Given an object structure like the one below: type IObject = { id: string, path: string, children?: IObject[] } const tree = [ { id: 'obj1' as const, path: 'path1' as const, children: [ { id: &ap ...

Using NestJS to pass request and response parameters

I have a function in my services set up like this: ` @Injectable() export class AppService { getVerifyToken(req: Request, res: Response) { try { let accessToken = process.env.ACCES_TOKEN_FB; let token = req.query["hub.verify_t ...

Utilizing Angular to enhance tracking page views with the latest Google Analytics integration

I have been using various Angular applications to track page views, implementing a strategy similar to the one outlined in this blog post. In order to avoid third party references, I will provide the relevant code snippets here. To include the gtag depen ...

Steps for securing a Web API within an Angular client application

I am currently developing an Angular application that allows anonymous users to complete forms, make payments, and purchase products without requiring a login form. The Angular application interfaces with a Web Api built in Asp .net core to handle the retr ...

Tips for keeping your cool when a listener is suggesting changing it to a const variable

How can I output the isChecked value to the parent component? This value indicates whether the checkbox is clicked or not. Unfortunately, changing it to const is not an option due to an assignment below. My linter is suggesting that I change it to const, ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: https://i.sstatic.net/C81tg.png The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there ma ...

Angular Material Stepper Design Styling Guide

https://i.sstatic.net/8R93n.pnghttps://i.sstatic.net/VxzP3.png Hello, I am interested in customizing the angular material stepper UI similar to the image provided. I would like to know if it is possible to programmatically change the icon. In case of an e ...

Navigating through an interface array using *ngFor in TypeScript

After successfully implementing an interface to retrieve data from a service class, I encountered an issue when attempting to iterate through the FilteredSubject interface array. Despite using console.log, I was unable to achieve the desired outcome. You ...

The selected attribute does not function properly with the <option> tag in Angular

Currently, I am faced with a challenge involving dropdowns and select2. My task is to edit a product, which includes selecting a category that corresponds to the product. However, when I open the modal, the selected group/category is not displayed in the d ...

Angular 13: SyntaxError Encountered: Token 'export' Not Recognized

After upgrading Angular from version 12 to 13, I encountered an error when running the app: "Uncaught SyntaxError: Unexpected token 'export'." Here are some additional details for context: In the angular.json configuration file, I had specified ...

Attempting to create a login feature using phpMyAdmin in Ionic framework

Currently, I am in the process of developing a login feature for my mobile application using Ionic. I am facing some difficulties with sending data from Ionic to PHP and I can't seem to figure out what the issue is. This is how the HTML form looks li ...

The parameter type must be a string, but the argument can be a string, an array of strings, a ParsedQs object, or an array of ParsedQs objects

Still learning when it comes to handling errors. I encountered a (Type 'undefined' is not assignable to type 'string') error in my code Update: I added the entire page of code for better understanding of the issue. type AuthClient = C ...

Tips for Looping through an Object within another Object

Is there a way to retrieve values from an Object that contains another Object nested inside? I am not overly concerned about the keys, but it would be helpful if I could access them as well. Here is an example of the response: res = {data: {name: 'na ...

Leverage ngrx to streamline action creation for multiple feature modules

My Angular 5 application consists of multiple feature modules, each responsible for assets on specific pages and lazily loaded. src/ |--app/ |--core/ <-- core functionality here |--landing/ |--store/ |--about-us/ Each module has a top-leve ...

Can classes be encapsulated within a NgModule in Angular 2/4?

Looking to organize my classes by creating a module where I can easily import them like a separate package. Take a look at this example: human.ts (my class file) export class Human { private numOfLegs: Number; constructor() { this.numOfLegs = 2 ...

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

Tips for effectively managing 404 errors in Angular 10 with modular routing

I'm facing challenges with handling 404 pages within an Angular 10 application that utilizes modular routing architecture. Here is the structure of my code: |> app |-- app.module.ts |-- app-routing.module.ts |-- app.component{ts, spec.ts, scss, ht ...

What potential issues should I be aware of when I install new node packages?

I encountered an error message when trying to install a Node Package. Running npm install shows that everything is up to date. https://i.stack.imgur.com/d78hf.png ...