How to refresh a page in Angular Typescript to wait for HTTP calls from the backend

Looking at the code snippet below:

  1. The initial HTTP call retrieves multiple IDs of orderlines (items).
  2. For each ID, another HTTP call is made to reserve them. Afterward, the page needs to be updated to display the reserved items.

When dealing with a large number of items, there was an issue where the page would reload before the reservations were completed on the backend. To address this, a delay of 0.7 seconds was added, but this is not considered best practice. I am exploring other options like switchMap to improve this process.

   this.service.getOrderlineId(this.orderlineIds).subscribe((ids: Number[]) => {
      ids.forEach(id => {
        this.currentReservation = {
          orderline: id,
          company: this.currentUser.company_id,
          company_name: this.currentCompany.name,
          user: this.currentUser.user_id,
          delivery_address: this.currentCompany.address
        }
        this.service.createOrderLineReservation(this.currentReservation).subscribe(reservation => {

        })
      })
    })

    setTimeout(() => {                       
      this.clearGroups();
      this.prepareRow();
      this.prepareGroups();
    }, 700);

Answer №1

To manipulate the streams, you have the option of utilizing Rxjs's pipe functionality

this.service
  .getOrderlineId(this.orderlineIds)
  .pipe(
    map((ids: number[]) =>
        // Transform the ids to an Observable list
      ids.map((id) =>
        this.service.createOrderLineReservation({
          orderline: id,
          company: this.currentUser.company_id,
          company_name: this.currentCompany.name,
          user: this.currentUser.user_id,
          delivery_address: this.currentCompany.address,
        })
      )
    ),
    switchMap((reservations$: Observable[]) => 
    // Combine all emitted observables into an array
    zip(...reservations$))
  )
  .subscribe((reservations: Reservation[]) => {
      // Receive a sorted list of reservations

      this.clearGroups();
      this.prepareRow();
      this.prepareGroups();
  });

ps: Avoid using setTimout function

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

Utilizing a Link element in conjunction with ListItem and Typescript for enhanced functionality

I am currently using material-ui version 3.5.1 My goal is to have ListItem utilize the Link component in the following manner: <ListItem component={Link} to="/some/path"> <ListItemText primary="Text" /> </ListItem> However, when I tr ...

How to assign ngModel to a nested component in Angular?

If I have a component called InputComponent, which implements the ControlValueAccessor interface. Now, another component named AnotherComponent uses the InputComponent like this: <my-input [(ngModel)]="text"></my-input> While testing AnotherC ...

Spectral request for Ajax

I am in the process of creating a website using PHP and Ajax. I need to send an ajax request that could potentially take up to 5 minutes to complete. However, I do not require any response from this request, allowing users to freely navigate around my webs ...

Is it considered poor practice in TypeScript to manually set the type when the type inference is already accurate?

Is it necessary to explicitly set the variable type in TypeScript when it is inferred correctly? For example: const add = (a: number, b: number) => a + b; const result = add(2, 3); // Or should I explicitly declare the return value type? const add = ...

Error TS2488 in React TypeScript: The data type 'IStateTypes' is required to have a method called '[Symbol.iterator]()' that returns an iterator

At the moment, I am working on implementing a global state in React Hooks but have run into an issue. https://i.stack.imgur.com/DN83K.png The current problem I'm facing is with [Symbol.iterator](. I am uncertain about how to resolve this as I am in ...

What is the significance of having both nulls in vue's ref<HTMLButtonElement | null>(null)?

Can you explain the significance of these null values in a vue ref? const submitButton = ref<HTMLButtonElement | null>(null); ...

Determine the data type of the value for the mapped type

Is there a way to access the value of a type like the following: interface ParsedQs { [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[] } I am looking for a method to retrieve the ParsedQsValue type without directly duplicating it from ...

If a task is currently ongoing, be sure to subscribe to it; otherwise, restart it

If I have a long-running observable called longObservable, which emits a new string once after 5 seconds and then completes. longObservable(): Subject<string> { return timer(5000).pipe{ map(() => randomString()) } } Other pages c ...

Why does the data appear differently in Angular 9 compared to before?

In this particular scenario, the initial expression {{ bar }} remains static, whereas the subsequent expression {{ "" + bar }} undergoes updates: For example: two 1588950994873 The question arises: why does this differentiation exist? import { Com ...

Assigning string properties to different types

I have numerous data types, each with a common property called dataType, and I am currently mapping each one to that specific value: interface GroupData { dataType: "group"; name: string; people: PersonData[]; } interface PersonData ...

Different categories of "areas" found in TypeScript within Visual Studio 2013

In C#, we often use "regions," but unfortunately that feature is missing in TypeScript. Is there a way to group code sections in TypeScript? I came across this article on Stack Overflow discussing the absence of regions in TypeScript. I'm curious if ...

How can I easily move from a shared page to a specific page in Angular 8?

Just stepping into the world of front-end development, I have a scenario where my menu page offers 3 options to navigate: Go to Arena. Go to Dungeon. Go to Battleground. However, clicking on any of these options leads me to a common page for character p ...

Is there a way to attach a ref to a Box component in material-ui using Typescript and React?

What is the best way to attach a ref to a material-ui Box component in React, while using TypeScript? It's crucial for enabling animation libraries such as GreenSock / GSAP to animate elements. According to material-ui documentation, using the itemRef ...

Learn how to dynamically include files within the script tag using Angular4

Is there a way to dynamically include a remote file in a script tag using Angular4? For instance, if I have a file named https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js as a query string parameter in the URL located in the address bar http: ...

What is the reason for TypeScript not providing warnings for unrealistic conditions involving 'typeof' and 'in'?

The recent updates in version 4.9 highlighted the enhanced narrowing with 'in'. Intrigued by this, I decided to experiment with their example in a coding playground. Surprisingly, I discovered that seemingly impossible conditions involving typeof ...

Turn off Typescript compilation in Visual Studio for a webpage

My Angular website (not a computer science project) is integrated into a solution, causing Visual Studio 2019 to generate multiple TypeScript compilation errors while working on other projects within the same solution. You can see examples of these errors ...

Implementing Observable lambdas in Angular templates for easy function calling

Within a component, I have the following code snippet: public hasFoo$: Observable<(name: string) => boolean> = ... Now, I would like to use this multiple times in my template with a stepper: <mat-vertical-stepper> <mat-step *ngIf="ha ...

Enhance your JavaScript code by replacing Promise syntax with Async syntax and utilizing map() instead of a traditional For

I have a code snippet here that is functioning properly. However, I am interested in converting the Promise code in the middle of the function to Async code and replacing the for loop with map(). Can someone guide me on how to achieve this transformation ...

Invoke a general function with corresponding generic parameters

I am currently working on a function that takes another function and its arguments as parameters, then runs the function with the provided arguments and returns the result while maintaining the data types. If the function being provided has a fixed return ...

What is the best way to conceal an element solely in live production environments?

Is there a way in my Angular code to specifically target the PROD environment? <div *ngIf="environment !== 'prod'" class="col-6"> <button class="btn btn-primary text-white add-photo" (cli ...