Tips for handling delayed HTTP API responses in Angular

While working on my project, I encountered a delay in response when using the

this.ServiceHandler.getTxnInfo([], params)
API. To handle this, I implemented the use of setTimeout along with async/await. Despite these modifications, my promise ended up being rejected.

bookingInfo = [];

  timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

This segment showcases the API request being made to retrieve booking information.

async getBookingInfo(dateType: string) {
    const params = [];
    params.push({code: 'dateType', name: dateType});
    params.push({code: 'fromDate', name: '2019-01-01'});
    params.push({code: 'toDate', name: '2019-05-31'});
    return await this.ServiceHandler.getTxnInfo([], params).toPromise();
  }

getBookingDetails() {
    this.timeout(150057 ).then(() => this.getBookingInfo('BOOKING').then(
      bookings => {
        console.log(bookings);
      }));
  }

Unfortunately, when trying to print out console.log(bookings);, the promise gets rejected and the get requests fail. I encountered the following error message: https://i.sstatic.net/jQgmz.png

Any insights on how I can resolve this issue would be greatly appreciated.

Answer №1

By implementing the async and await keywords in your code, you can achieve the desired functionality.


async fetchReservationInformation(dateType: string) {
 const parameters = [];
 parameters.push({type: 'dateType', value: dateType});
 parameters.push({type: 'fromDate', value: '2019-01-01'});
 parameters.push({type: 'toDate', value: '2019-05-31'});
 return await this.ReservationService.fetchTransactionInfo([], parameters).toPromise();
}

async retrieveBookingDetails() {
 await this.fetchReservationInformation('BOOKING').then(
  bookings => {
    console.log(bookings);
 });
}

Answer №2

In order to make this code more suitable for Angular and avoid promises, let's modify it. There is no need to change observables to promises using toPromise()

fetchBookingData(dateType: string): Oservable<SOME_TYPE_HERE> {
  const params = [];
  params.push({code: 'dateType', name: dateType});
  params.push({code: 'fromDate', name: '2019-01-01'});
  params.push({code: 'toDate', name: '2019-05-31'});
  return this.ServiceHandler.getTxnInfo([], params);
}

retrieveBookingInformation(): void {
  this.fetchBookingData('BOOKING').subscribe(bookings => {
    console.log(bookings);
  });
}

Let's test this code without promises to see if it functions correctly. If it doesn't, we can eliminate promises as the potential cause.

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

The function item$.take cannot be found, resulting in a TypeError: "item$.take is not a function"

I am currently facing an issue with the take(1) function not working as expected with my Angular Firebase object. I have tried using valuechanges and snapshotchanges as alternatives, but they do not solve the problem for me due to other issues I encounter. ...

Component library's Angular 7 Package dependencies

After developing a component library in Angular 7, I encountered an issue when trying to port it to other applications. Even though the Angular library was installed within the component library, it wasn't being bundled with the components for use in ...

Mastering the Rejection of Promises in Javascript with Graceful Elegance

One effective pattern using ES2017 async/await involves: async function () { try { var result = await some_promised_value() } catch (err) { console.log(`This block will be processed in a reject() callback with promise patterns, which is far mo ...

Ways to showcase my select/option in Angular 14?

My select input is not displaying and I'm struggling to understand why. Despite seeing it in the inspector, it remains hidden... I initially attempted to retrieve data from my service, which failed. Then, I experimented with placing static data direc ...

What methods can be used to avoid getting distracted by input?

Is there a way to prevent the input field in angular-material2 from gaining focus when clicking on a visibility button? To see an example of how it works, visit: material.angular.io Image before pressing the button: https://i.stack.imgur.com/5SmKv.png ...

What is the method to cancel an Observable subscription without having a reference to the object of type "Subscription"?

If I were to subscribe to an Observable without an object of type "Subscription," how can I properly unsubscribe from it? For instance, if my code looks something like this: this.subscription = bla ... I know I can easily unsubscribe using the following ...

Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code: enum UserRole { CONSULTANT, MANAGER, ... } There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user: [ "CONSU ...

unable to retrieve information from the redis cache

Attempting to retrieve data from cache using the readData function in the controller file. Encountering an issue where the someVal variable is initially undefined after calling readData, but eventually gets populated with data after receiving a callback ...

Tips for effectively handling the data received from a webservice when logging into a system

My web service provides me with permissions from my user. The permissions are stored as an array in JSON format. I need to find a way to access and display this data in another function. {"StatusCode":0,"StatusMessage":"Authenticated Successfully", "Token ...

Checking that an object's keys are all present in an array in TypeScript should be a top priority

I am working with a const object that is used to simulate enums. My goal is to extract the keys from this object and store them in an array. I want TypeScript to generate an error if any of these keys are missing from the array. // Enum definition. export ...

Learn the process of generating an ID and dynamically updating its content using Angular

I have a coding challenge where I need to dynamically create an ID and retrieve it in order to change its content upon clicking. Here is the code snippet: <div class="row" *ngFor="let row of [1, 2, 3]"> <button (click)=&quo ...

Solve TypeScript React error TS(2339) by resolving issues with extending a React.FC and using static property of type JSX.Element for uninitialized components

Currently, in VSCode, the typescript compiler is at TypeScript React 4.4.2 and it's pointing to a TS(2339) error: Property 'Col' does not exist on type 'FC<GridProps>'. I have attempted to add this prop to GridProps: export ...

What is the process for declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

When sending a POST request in Angular and Node.js, the req.body object is found to be empty {}

Presenting My Service Module import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Items } from "./inventory.model"; import { Router } from "@angular/router"; impor ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

Changing the default font size has no effect on ChartJS

I'm trying to customize the font size for a chart by changing the default value from 40px to 14px. However, when I set Chart.defaults.global.defaultFontSize to 14, the changes don't seem to take effect. Below is the code snippet for reference. An ...

Tips for preserving data in Angular form fields

Within my angular application, a scenario exists where two pages are involved. On the initial page, users input data into a form and proceed by clicking "continue" which leads them to the subsequent page. The following page features a back button that ena ...

In React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

Acquiring the Auth0 authentication token

Currently, I am using the Angular SDK of Auth0 and everything seems to be functioning correctly except for retrieving the token. At the moment, I am manually obtaining the token from my dashboard. The method in Auth0Service called getAccessTokenSilently i ...