What is the best way to halt numerous requests in progress in Angular?

I have a function called getList() in the SearchService:

  public getList() {
    // HTTP POST call as an observable
    // Pipe with a few map transformations
  }

When initializing my ListComponent, I create an Observable like this:

 ngOnInit(): void {
    list$ = searchService.getList();    
  }

Then, I subscribe to the observable in the template using the async pipe:

<ng-container *ngIf="list$ | async as list; else showSpinner">
   <!-- Content here -->
</ng-container>

Surprisingly, even though this is the only place where I subscribe to the list$ observable, I notice two requests when checking Dev Tools: https://i.sstatic.net/WTzC1.png

My troubleshooting steps so far:

  1. I've searched similar questions on StackOverflow but none of the answers seem to solve my issue.

  2. Adding ChangeDetectionStrategy.OnPush didn't provide a solution either.

  3. I've experimented with various methods like share, shareReplay, publishReplay, refCount, delay, debounceTime, distinctUntilChanged, take, first on the getList() function and list$ observable without success.

What could be causing this unexpected behavior?

Answer №1

An effective method to detect existing requests using a variable

  let requestOccured:any = null;
  class Bar {
    public retrieveList() {
      if (requestOccured) return requestOccured;
      requestOccured = initiateRequest();
      return requestOccured;
    }
  }

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

Applying Multiple Conditions to setCellProps in Material-UI

I am facing an issue with a data-table that is not in a class extending the React.Component, unlike some examples I have come across. My goal is to setCellProps based on certain conditions as outlined below: If utilization is less than or equal to 50, the ...

Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png Below is the code snippet: HTML ...

What is the best way to link multiple select tags in an HTML document?

I am working with a data grid that contains student information such as Name, Class, and Score. Each row has a checkbox for selection. The requirement is that when the user selects one or more rows and clicks on the "show information" Button, a new windo ...

The parameter type 'string | null' cannot be assigned to the argument type 'string'. The type 'null' is not compatible with the type 'string'.ts(2345)

Issue: The parameter type 'string | null' is not compatible with the expected type 'string'. The value 'null' is not a valid string.ts(2345) Error on Line: this.setSession(res.body._id, res.headers.get('x-access-token&ap ...

Navigate through the router using query parameters in Angular 5

Encountering an issue with routing to a route containing query params. Here is the function in question: goToLink(link) { this.router.navigate([`${link.split('?')[0]}`, { queryParams: this.sortParams(link)}]); } Additionally, there is anoth ...

Encountering difficulties setting a value to a key within an Object in Angular/Typescript

I'm currently working with Angular, and I've encountered an issue while trying to assign a value to a key within my model. Here's a snippet of my code: export class aa{ types: bb[]; } export interface bb{ name: string; age: str ...

How can I designate the first enum value as 1 in a protobuf data structure?

In order to resolve an issue in the dropdown component of Primeng, the first enum value in protobuf must be set to 0. However, this is causing some trouble. Is there a method to change the first enum value to 1 instead? ...

Error in TypeScript: The type 'event' is lacking the following properties compared to type 'KeyboardEvent'

I've created a custom event listener hook with the following structure: const useEventListener = ( eventName: string, handler: ({key} : KeyboardEvent) => void, ) => { const savedHandler = useRef<({key} : KeyboardEvent) => void>(ha ...

Move data and information between various software programs

When using nrwl schematics, various apps are generated: Faculty Organization Students Let's say there is a functionality (lib) called "createStudents" in the Students app that also needs to be included in the Faculty app. There are two possible app ...

At first, Typescript generics make an inference but are ultimately specified

In my TypeScript code, I have defined a custom Logger class with specific options. The DefaultLevel type is created as a union of 'info' and 'error'. The LoggerOptions interface includes two generics, CustomLevels and Level, where Custo ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...

Unable to transfer props object to React component using TypeScript

Apologies if this seems like a basic issue, but I've been struggling with it for the past two days. I'm currently working on writing a simple unit test in Vitest that involves rendering a component to the screen and then using screen.debug(). The ...

Having trouble with Socket.io sending data to a specific socketId?

I'm currently using Socket.Io 1.7.3 with Angular 2, connecting to a ExpressJS Server. I'm facing an issue where I am unable to send packages to a specific socket ID even though they are a match. Server code snippet: socket.on('subscribeNot ...

Is there a way to trigger the opening of the mat-autocomplete panel when an option is selected in a different mat-autocomplete component?

Is it possible to trigger the opening of a mat-autocomplete panel when an option is selected in another mat-autocomplete? To see an example, please check out this demo. ...

What's the best way to track changes in multiple form fields simultaneously in Angular?

Situation I have a form with 8 fields, but I want to monitor changes in just three of them to apply the same function. I don't want to set up individual subscriptions for each field like this: this.headerForm.get('start').valueChanges.subsc ...

Error encountered: "Injection error: Angular2 + typescript + jspm : No provider found for Http ( App -> Provider -> Http )"

I am in the process of transitioning from Webpack to JSPM with system.js. Our application has a simple App component. I have been following the steps outlined in this article Angular 2 Starter Setup with JSPM, SystemJS and Typescript in atom (Part 1) impo ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

Is there a way to access a function or variable from within the scope of $(document)?

Whenever I attempt to utilize this.calculatePrice, it does not work and I am unable to access the external variable minTraveller from within the function. numberSpin(min: number, max: number) { $(document).on('click', '.number-spinner b ...

After migrating from Angular 11 to Angular 12, I am facing issues with compiling my project using optimization parameters

Recently, I upgraded an environment using nrwl from angular version 11 to 12 including two angular applications and multiple libraries. Upon updating, I encountered an issue when trying to compile with optimization settings: angular.json { .... "op ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...